🌐
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
How to build an Image using Docker API Python Client? - Stack Overflow
I just have started Docker Api and explored various parts.But I'm stuck to build an image using docker api by using python client, actually I couldn't understand how to setup various required argum... 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
🌐
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....
🌐
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.
🌐
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
Find elsewhere
🌐
Ben Postance
bpostance.github.io › posts › docker-fask-api
How to containerize a simple Rest API using Python Flask | Ben Postance
April 19, 2021 - Now when you inspect running dockers you will see your container. And visit http://localhost:5000/ or http://localhost:5000/api?value=2 to visit your api.
🌐
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%
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.

🌐
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
🌐
GitHub
github.com › aio-libs › aiodocker
GitHub - aio-libs/aiodocker: Python Docker API client based on asyncio and aiohttp · GitHub
pip install -U build python -m build --sdist --wheel ... import asyncio import aiodocker async def list_things(docker): print('== Images ==') for image in (await docker.images.list()): tags = image['RepoTags'][0] if image['RepoTags'] else '' print(image['Id'], tags) print('== Containers ==') for container in (await docker.containers.list()): print(f" {container._id}") async def run_container(docker): print('== Running a hello-world container ==') container = await docker.containers.create_or_replace( config={ 'Cmd': ['/bin/ash', '-c', 'echo "hello world"'], 'Image': 'alpine:latest', }, name='testing', ) await container.start() logs = await container.log(stdout=True) print(''.join(logs)) await container.delete(force=True) async def main(): docker = aiodocker.Docker() await list_things(docker) await run_container(docker) await docker.close() if __name__ == "__main__": asyncio.run(main())
Starred by 522 users
Forked by 112 users
Languages   Python
🌐
PyPI
pypi.org › project › docker
docker · PyPI
Details for the file docker-7.1.0-py3-none-any.whl.
      » pip install docker
    
Published   May 23, 2024
Version   7.1.0
🌐
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:
🌐
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.
🌐
HeyCoach Blog
heycoach.in › blog › docker-api-in-python
Docker API in Python: A Friendly Guide
December 27, 2024 - To use the Docker API in Python, you’ll need to install the docker package. It’s as easy as pie (or cake, if you prefer). Here’s how you do it: ... Once you’ve installed the package, you can start interacting with the Docker API. Here’s a simple example to get you started:
🌐
Medium
medium.com › @qazbnm456 › play-with-docker-engine-api-using-python-a2d8d9a155a8
Play with Docker Engine API using Python | by Boik Su | Medium
September 15, 2017 - Most of the client’s commands map directly to API endpoints (e.g. docker ps is GET /containers/json). The notable exception is running containers, which consists of several API calls.