🌐
Docker Docs
docs.docker.com › reference › docker engine api › sdk › examples
Examples using the Docker Engine SDKs and Docker API
package main import ( "context" "io" "log" "os" "github.com/moby/moby/api/pkg/authconfig" "github.com/moby/moby/api/types/registry" "github.com/moby/moby/client" ) func main() { ctx := context.Background() apiClient, err := client.New(client.FromEnv, client.WithUserAgent("my-application/1.0.0")) if err != nil { log.Fatal(err) } defer apiClient.Close() authStr, err := authconfig.Encode(registry.AuthConfig{ Username: "username", Password: "password", }) if err != nil { log.Fatal(err) } out, err := apiClient.ImagePull(ctx, "alpine", client.ImagePullOptions{RegistryAuth: authStr}) if err != nil { log.Fatal(err) } defer out.Close() io.Copy(os.Stdout, out) } The Python SDK retrieves authentication information from the credentials store file and integrates with credential helpers. It's possible to override these credentials, but that's out of scope for this example guide.
🌐
Docker
docker-py.readthedocs.io
Docker SDK for Python — Docker SDK for Python 7.1.0 documentation
It lets you do anything the docker command does, but from within Python apps – run containers, manage containers, manage Swarms, etc. For more information about the Engine API, see its documentation.
Discussions

dockerpy - link containers with the docker python API - Stack Overflow
I want to use the docker python API (pip install docker-py) to create a container and link it to an existing container which I created with docker-compose. Using the command line this is easy: do... More on stackoverflow.com
🌐 stackoverflow.com
Dockerizing an API built with python on local machine - Stack Overflow
I have cloned a repository of an API built with python on my local machine and my goal is to be able to send requests and receive responses locally. I'm not familiar python but the code is very readable and easy to understand, however the repository contains some dependencies and configuration files to Dockerise ... More on stackoverflow.com
🌐 stackoverflow.com
Issue with Python Docker SDK
Yeah, I just started seeing this on the CI for one of my projects: https://app.circleci.com/pipelines/github/simplistix/testservices/530/workflows/a5bd922a-beb0-4aa7-9efc-db1c78fa1abf/jobs/3804 Seems like a new thing as of about a day ago :-/ Looks like a bug in docker-py caused by a new release of the requests library: https://github.com/docker/docker-py/issues/3256 pin the requests package to <2.32 should fix it. More on reddit.com
🌐 r/docker
8
7
May 21, 2024
Update a docker container using an api, or python sdk
Python Docker SDK should be just a wrapper on the Docker API (I don’t know how good the abstractions are, I just used it to manage some images and tags, no containers) You can always borrow some inspiration from Watchtower code and see if you can replicate the process with Python Docker SDK. More on reddit.com
🌐 r/selfhosted
5
2
July 9, 2024
🌐
GitHub
github.com › docker › docker-py
GitHub - docker/docker-py: A Python library for the Docker Engine API · GitHub
A Python library for the Docker Engine API. Contribute to docker/docker-py development by creating an account on GitHub.
Starred by 7.2K users
Forked by 1.7K users
Languages   Python
🌐
DEV Community
dev.to › francescoxx › python-fullstack-rest-api-app-with-docker-1101
Python 🐍 fullstack REST API app with Docker 🐳 - DEV Community
January 6, 2024 - test: just a test route create a user: create a user with a name and an email get all users: get all the users in the database get one user: get one user by id update one user: update one user by id delete one user: delete one user by id All the routes have error handling, for example if the user is not found, we will return a 404 HTTP response. ... The flask.dockerfile file is the file that will be used to containerize the Flask application. Create a file called flask.dockerfile in the backend folder and add the following content: FROM python:3.6-slim-buster WORKDIR /app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY .
🌐
MetricFire
metricfire.com › blog › develop-and-deploy-a-python-api-with-kubernetes-and-docker
Comprehensive Guide to Developing and Deploying a Python API with Docker and Kubernetes (Part I) | MetricFire
May 14, 2025 - We finally exposed port 5000, since our app will use this port, and we launched the python command with our app.py as an argument. This will start the API when the container starts.
🌐
Docker
docker-py.readthedocs.io › en › stable › api.html
Low-level API — Docker SDK for Python 7.1.0 documentation
>>> import docker >>> client = ... u'Version': u'17.10.0-ce'} ... base_url (str) – URL to the Docker server. For example, unix:///var/run/docker.sock or tcp://127.0.0.1:1234....
🌐
Ben Postance
bpostance.github.io › posts › docker-fask-api
How to containerize a simple Rest API using Python Flask | Ben Postance
April 19, 2021 - This post demonstrates how to setup a simple Docker container to run an API using Python Flask.
Find elsewhere
🌐
Predictivehacks
predictivehacks.com › how-to-use-docker-for-flask-api
Docker + Flask | Dockerizing a Python API – Predictive Hacks
You made it! You’ve just dockerized your Flask API! Simple as that. ... CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES fe7726349933 image_name "python ./main.py" About an hour ago Up About an hour 0.0.0.0:5000->9007/tcp eager_chaum
Top answer
1 of 3
4

https://github.com/docker/docker-py

A Python library for the Docker Remote API. It does everything the docker command does, but from within Python – run containers, manage them, pull/push images, etc.

create_container:

Creates a container that can then be .start() ed. 
Parameters are similar to those for the docker run 
command except it doesn't support the attach options (-a).

The source code of create_container

def create_container(self, image, command=None, hostname=None, user=None,
                     detach=False, stdin_open=False, tty=False,
                     mem_limit=None, ports=None, environment=None,
                     dns=None, volumes=None, volumes_from=None,
                     network_disabled=False, name=None, entrypoint=None,
                     cpu_shares=None, working_dir=None, domainname=None,
                     memswap_limit=None, cpuset=None, host_config=None,
                     mac_address=None, labels=None, volume_driver=None,
                     stop_signal=None, networking_config=None):

But I found links at start function:

def start(self, container, binds=None, port_bindings=None, lxc_conf=None,
          publish_all_ports=None, links=None, privileged=None,
          dns=None, dns_search=None, volumes_from=None, network_mode=None,
          restart_policy=None, cap_add=None, cap_drop=None, devices=None,
          extra_hosts=None, read_only=None, pid_mode=None, ipc_mode=None,
          security_opt=None, ulimits=None):

So I think you should:

from docker import Client
>>> cli = Client(base_url='tcp://127.0.0.1:2375')
>>> container = cli.create_container(
...     image='busybox:latest',
...     command='/bin/sleep 30')
>>> response = cli.start(container=container.get('Id'),links=[('EXISTING_CONTAINER', 'LINK_NAME')])

The working example (DO)

I am using CoreOS on DO:

  1. run docker container and mount inside the /var/run/docker.sock from host
  2. install tools
  3. run test container EXISTING_CONTAINER
  4. run python example

The set of commands:

docker run -it -v /var/run/docker.sock:/var/run/docker.sock ubuntu:12.04 bash
apt-get update;apt-get install python-pip -y;pip install docker-py
docker run -d --name EXISTING_CONTAINER busybox   sh -c "while true; do sleep 1;done"

Python example

from docker import Client
cli = Client(base_url='unix://var/run/docker.sock', version='auto')
container = cli.create_container(
image='busybox:latest',
command='/bin/sleep 30')
response = cli.start(container=container.get('Id'),links=(('EXISTING_CONTAINER', 'LINK_NAME'))

The result on host:

wp-coreos-512mb-ams2-01 ~ # docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
2f58e661579d        busybox             "sh -c 'while true; d"   23 seconds ago      Up 22 seconds                           EXISTING_CONTAINER
6f08dd3f5017        busybox:latest      "/bin/sleep 30"          9 minutes ago       Up 5 seconds                            condescending_brown
2 of 3
2

Yes, the networking documentation for docker-py is seriously lacking - the maintainers agree (https://github.com/docker/docker-py/issues/982 for a global alias example).

Note that Valeriy's answer above will create a legacy link, which might (will in my case) lead to issues if you use a non-default network such as the ones created by docker-compose.

In any case, adding parameters to Client.start is depreciated.

The new way to do this can be found in the unitttest: https://github.com/docker/docker-py/blob/master/tests/integration/network_test.py#L190-213

@requires_api_version('1.22')
def test_create_with_links(self):
    net_name, net_id = self.create_network()

    container = self.create_and_start(
        host_config=self.client.create_host_config(network_mode=net_name),
        networking_config=self.client.create_networking_config({
            net_name: self.client.create_endpoint_config(
                links=[('docker-py-test-upstream', 'bar')],
            ),
        }),
    )

    container_data = self.client.inspect_container(container)
    self.assertEqual(
        container_data['NetworkSettings']['Networks'][net_name]['Links'],
        ['docker-py-test-upstream:bar'])

    self.create_and_start(
        name='docker-py-test-upstream',
        host_config=self.client.create_host_config(network_mode=net_name),
    )

    self.execute(container, ['nslookup', 'bar'])

Valeriy's Example would then look as follows:

Python Example

from docker import Client
cli = Client(base_url='unix://var/run/docker.sock', version='auto')

# Note: 'bridge' is the default network
net_config = cli.create_networking_config(
        {'bridge': self.docker_client.create_endpoint_config(
            links=[('EXISTING_CONTAINER', 'LINK_NAME')]
        )}
    )

container = cli.create_container(
  image='busybox:latest',
  command='/bin/sleep 30',
  network_configuration=net_config 
)
response = cli.start(container=container.get('Id'))

I have not tested this specific code, but this is the way I have been able to connect a new container to an existing container, whereas the existing one had been created by compose into a network "project_default"

You might also want to check this link for more information and background.

🌐
GitHub
github.com › nanic › python-rest-api-docker
GitHub - nanic/python-rest-api-docker: python
Note: If the image is built inside a private network, you can mention gateway to proxy through Ex: docker build --build-arg proxy=hostname:port -t python-rest . ... import requests r = requests.post('http://0.0.0.0:5000/v1/api',verify=False, ...
Starred by 3 users
Forked by 10 users
Languages   Python 79.6% | Shell 20.4% | Python 79.6% | Shell 20.4%
🌐
Josefjebavy
blog.josefjebavy.cz › en › programming › docker-api-python
Python program to control Docker using the API
April 3, 2024 - A complete video demonstration of how to prepare and run a Python application that will list all running docker containers. And other ways to use the Docker API:
🌐
PyPI
pypi.org › project › docker-py
docker-py · PyPI
Download URL: docker_py-1.10.6-py2.py3-none-any.whl
      » pip install docker-py
    
Published   Nov 02, 2016
Version   1.10.6
Top answer
1 of 1
1

Adjust Dockerfile

Assuming all code is in the /app directory you have already copied over all your code and installed all the dependencies required for the application.

But you are missing - at least (see disclaimer) - one essential line in the Dockerfile which is actually the most important line as it is the CMD command to tell Docker which command/ process should be executed when the container starts.

I am not familiar with the particular base image you are using (which is defined using the FROM command) but after googling I found this repo which suggests the following line, which does make a lot of sense to me as it starts a web server:

# open port 80 on the container to make it accesable from the outside
EXPOSE 80
# line as described in repo to start the web server
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]

This should start the web server on port 80 using the application stored in a variable app in your main.py when the container starts.

Build and run container

When you have added that you need to build your image using docker build command.

docker build -t asmoun/my-container .

This builds an container image asmoun/my-container using the Dockerfile in the current directory, hence the .. So make sure you execute that when in the directory with the Dockerfile. This will take some time as the base image has to download and dependencies need to be installed.

You now have an image that you can run using docker run command:

docker run --name my-fastapi-container -d -p 80:80 asmoun/my-container

This will start a container called my-fastapi-container using the image asmoun/my-container in detached mode (-d option that makes sure your TTY is not attached to the container) and define a port mapping, which maps the port 80 on the host to port 80 on the container, which we have previously exposed in the Dockerfile (EXPOSE 80).

You should now see some ID getting printed to your console. This means the container has started. You can check its state using docker ps -a and you should see it marked as running. If it is, you should be able to connect to localhost:80 now. If it is not use docker logs my-fastapi-container to view the logs of the container and you'll hopefully learn more.

Disclaimer

Please be aware that this is only a minimal guide on how you should be able to get a simple FastAPI container up and running, but some parameters could well be different depending on the application (e.g. name of main.py could be server.py or similar stuff) in which case you will need to adjust some of the parameters but the overall process (1. adjust Dockerfile, 2. build container, 3. run container) should work. It's also possible that your application expects some other stuff to be present in the container which would need to be defined in the Dockerfile but neither me, nor you (presumably) know this, as the Dockerfile provided seems to be incomplete. This is just a best effort answer.

I have tried to link all relevant resources and commands so you can have a look at what some of them do and which options/ parameters might be of interest for you.

🌐
Genui
genui.com › resources › python-api-development-in-docker
Python API Development in Docker - GenUI
A detailed walk-through of developing an API locally within a docker container.
🌐
Docker
docker.com › blog › how-to-dockerize-your-python-applications
How to “Dockerize” Your Python Applications | Docker
The Docker SDK for Python is another useful way to run docker commands within Python apps themselves. Are you a film buff who’s also eager to explore further? Check out Lorenzo Costa’s tutorial on quickly deploying your own Game of Thrones API with Flask, MongoDB, and other tools.
Published   November 6, 2024
🌐
PyPI
pypi.org › project › docker
docker · PyPI
A Python library for the Docker Engine API.
      » pip install docker
    
Published   May 23, 2024
Version   7.1.0
🌐
Medium
medium.com › @prateekbansalind › python-programs-4-dockerizing-your-flask-api-for-seamless-deployments-28c1842a92cb
Python Programs 4: Dockerizing Your Flask API for Seamless Deployments | by Prateek Bansal | Medium
August 14, 2023 - Here’s a Dockerfile tailored for our Flask API: # Use an official Python runtime as the base image FROM python:3.8-slim # Set the working directory in the container to /app WORKDIR /app # Copy the current directory (our Flask app) into the container at /app COPY .