It sounds like you're using docker-py.

Also, it sounds like maybe you're not familiar with TLS, so please read the documentation for using TLS with docker-py. You may need to download your TLS files and copy them local to the docker-py client as they are used to authenticate that you are authorized to connect to the Docker daemon.

I hope your remote Docker daemon is not exposed to the world.

If it is not running TLS (exposed to the world):

client = docker.Client(base_url='<https_url>', tls=False)

If it is secured with TLS (not exposed to the world):

client = docker.Client(base_url='<https_url>', tls=True)
Answer from taco on Stack Overflow
🌐
GitHub
github.com › docker › docker-py › issues › 1915
How to connect to a remote docker engine using this api in python? · Issue #1915 · docker/docker-py
February 20, 2018 - How to connect to a remote docker engine using this api in python?#1915 · Copy link · Labels · kind/question · yadneshk · opened · on Feb 20, 2018 · Issue body actions · I searched for this in the docs but didn't find anything about connecting to remote docker engine.
Author   yadneshk
Discussions

dockerpy - link containers with the docker python API - Stack Overflow
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. ... 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). ... def create_container(self, image, command=None, hostname... More on stackoverflow.com
🌐 stackoverflow.com
How to connect to Docker API from Docker container using Python? - Stack Overflow
I have difficulties on connecting to docker engine api using Python with official library docker from docker container. Always works fine in my machine, but when I build image and started with docker-compose handled error, that python can't connect to docker host. More on stackoverflow.com
🌐 stackoverflow.com
Hosting a Docker web app with a Python API
If your budget can stretch to ~$5/month, you could try pythonanywhere? It's obviously not 'self-hosted' though. Otherwise, host the app in a docker container or virtual machine and open up a/the port that others can use to access the app at the host's IP address. If you're at a research institute/university however, the IT/InfoSec department might have something to say about this if they've already said no to you before though. More on reddit.com
🌐 r/selfhosted
7
4
October 3, 2024
python - How to execute host's Docker command from container? - Stack Overflow
Why don't you just install Python on your host anyway ? ... $ docker run -v $(which docker):/usr/bin/docker -v /var/run/docker.sock:/var/run/docker.sock debian docker --version Docker version 1.7.0, build 0baf609 · Or set up docker to allow remote access (I can't find a good reference for this at the minute). You should also look at using the Docker API ... More on stackoverflow.com
🌐 stackoverflow.com
June 25, 2016
🌐
Docker
docker-py.readthedocs.io › en › stable › client.html
Client — Docker SDK for Python 7.1.0 documentation
Ensure the ssh client is installed and configured on the host. ... A client for communicating with a Docker server. ... base_url (str) – URL to the Docker server. For example, unix:///var/run/docker.sock or tcp://127.0.0.1:1234. version (str) – The version of the API to use.
🌐
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.
🌐
PyPI
pypi.org › project › docker-py
docker-py · PyPI
A Python library for the Docker Remote API.
      » pip install docker-py
    
Published   Nov 02, 2016
Version   1.10.6
🌐
Docker
docker-py.readthedocs.io › en › stable › api.html
Low-level API — Docker SDK for Python 7.1.0 documentation
Parameters are similar to those for the docker run command except it doesn’t support the attach options (-a). The arguments that are passed directly to this function are host-independent configuration options. Host-specific configuration is passed with the host_config argument.
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.

🌐
Google
chromium.googlesource.com › external › github.com › docker › docker-py › + › refs › tags › 0.5.1 › README.md
docker-py
Hits the /_ping endpoint of the remote API and returns the result. An exception will be raised if the endpoint isn't responding. ... Identical to the docker port command. ... Identical to the docker pull command. ... Identical to the docker push command. c.remove_container(container, v=False, link=False) ``` Remove a container. Similar to the `docker rm` command. ```python c.remove_image(image) ``` Remove an image.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 71276633 › how-to-connect-to-docker-api-from-docker-container-using-python
How to connect to Docker API from Docker container using Python? - Stack Overflow
docker.errors.DockerException: Error while fetching server API version: HTTPConnectionPool(host='127.0.0.1', port=2375): Max retries exceeded with url: /version (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f91bd81d6a0>: Failed to establish a new connection: [Errno 111] Connection refused')) docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory'))
🌐
Reddit
reddit.com › r/selfhosted › hosting a docker web app with a python api
r/selfhosted on Reddit: Hosting a Docker web app with a Python API
October 3, 2024 -

This may not necessarily fall under “self-hosted,” but I figured the people of this community would be able to give me some advice. I need to host a demo web app for a research project at work, but our IT/HPC department(s) said they don’t have the infrastructure to host a web app. The web app has a frontend web server and a backend Python API. I just need a service that can host the web app and offers various tiers of compute resources. Ideally, it would be able to spin up/down the API container depending on demand so we don’t have to pay for availability 24/7 (working at a university, budget is important). I looked into services like AWS and DigitalOcean, but they’re not quite what I’m after. If anyone has some advice, I’d appreciate it!

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.

🌐
Docker Docs
docs.docker.com › manuals › docker engine › daemon › configure remote access for docker daemon
Configure remote access for Docker daemon | Docker Docs
If you run a firewall on the same host as you run Docker, and you want to access the Docker Remote API from another remote host, you must configure your firewall to allow incoming connections on the Docker port.
🌐
DEV Community
dev.to › idevkamboj › access-docker-using-rest-api-pi
Access Docker Using Rest API - DEV Community
December 4, 2019 - But if you do not want to access Rest API remotely then you do not need to enable TCP. Then you can just use unix socket. $ curl --unix-socket /var/run/docker.sock http:/v1.24/containers/json [{ "Id":"ae63e8b89a26f01f6b4b2c9a7817c31a1b6196acf560f66586fbc8809ffcd772", "Names":["/tender_wing"], "Image":"bfirsh/reticulate-splines", ... }] You can use Python and Go as well here is the Example:
🌐
Ben Postance
bpostance.github.io › posts › docker-fask-api
How to containerize a simple Rest API using Python Flask | Ben Postance
April 19, 2021 - The arguments: change source directory to ‘/app’, bind a server socket ‘5000’, and assign our “flask-api” as the generic “app”. Nothing fancy here i’m using Conda but you could also use pip virtualenv. This is the file that we pass to Docker and lists the instructions used to build and execute our container. In a similar fashion to Git, Docker Hub hosts official and community developed Docker images for popular operating systems and deployments.
🌐
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 - This is the "docker-compose.yaml" file we are using with our API: version: '3.6' services: weather: image: weather:v1 ports: - "5000:5000" volumes: - .:/app ... In the above file, you can see that I configured the service "weather" to use the image "weather:v1." I mapped the host port 5000 to the container port 5000 and mounted the current folder to the "/app" folder inside the container.
🌐
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 - 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 . . EXPOSE 4000 CMD [ "flask", "run", "--host=0.0.0.0", "--port=4000"]
🌐
Docker Docs
docs.docker.com › reference › docker engine api
Docker Engine API | Docker Docs
Docker provides an API for interacting with the Docker daemon (called the Docker Engine API), as well as SDKs for Go and Python. The SDKs allow you to efficiently build and scale Docker apps and solutions.
🌐
Medium
medium.com › @shuklashubh818 › exploring-docker-py-a-python-library-for-docker-automation-8df5bc727fbe
Exploring Docker-Py: A Python Library for Docker Automation | by Shubh Prakash Shukla | Medium
February 15, 2024 - Docker-Py is a Python client library that allows developers to communicate with the Docker Engine’s Remote API programmatically.