Before writing python code, we need to make sure that our docker servers can be accessed by remote network.
By default, docker on Ubuntu20 is only accessible to the local machine. Take the following steps to make it remotely accessible:
Edit docker systemd config:
# "SYSTEMD_EDITOR=/bin/vi" tells "systemctl edit" to use vi.
# If you don't like vi, removing "SYSTEMD_EDITOR=/bin/vi" is ok.
SYSTEMD_EDITOR=/bin/vi systemctl edit docker.service
Write the following lines in the text input window, then save and exit:
[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H fd:// -H tcp://0.0.0.0:2375
Restart docker:
systemctl daemon-reload
systemctl restart docker.service
Check if you can access docker server by ip:
docker -H tcp://192.168.1.100:2375 ps
Replace "192.168.1.100" with your actual server ip.
Install python dependency:
pip install docker
Code example:
import docker
# replace "192.168.1.100" with your actual server ip.
client = docker.DockerClient(base_url='tcp://192.168.1.100:2375')
container = client.containers.run("redis", 'redis-server --maxmemory 256mb', ports={
'6379/tcp': 6379,
}, detach=True)
print(container.id)