In various situations you may in a need to control Docker outside of your host environment. Let’s say you’re deploying to a server of yours and to remote deploy you need a connection to your Docker Daemon. In that scenario Docker REST API connection comes to your rescue but with a little security cost. We’ll talk about that later in this post. But first let’s enable it. Assuming that you already have a server that has Docker installed on it.
Enabling Docker Remote API
/lib/systemd/system and edit the file
docker.service with your favourite terminal editor. Doesn’t matter whether you’re a super user or not. Find the line below and edit it like this:
ExecStart=/usr/bin/dockerd -H fd:// -H tcp://0.0.0.0:2376 --containerd=/run/containerd/containerd.sock
This way Docker engine server will be binded to Unix socket and TCP Port 2376. You can change the port however you want but be sure that it’s not being used by any other service on your machine.
After editing fire up these commands:
sudo systemctl daemon-reload sudo service docker restart
Now your remote API is enabled. Let’s test it.
Testing Docker Remote API Connection
Step outside from your server to anywhere else and now, you should be able to run these commands.
docker -H YOUR_SERVER_IP:2376 version
With a REST Client
Benefits and Advanced Usage
As dangerous as this can be (ops, spoilers for next chapter), this connection also offers some undeniable benefits. For example, from your CI agent you could say:
docker -H YOUR_SERVER_IP:2376 pull YOUR_IMAGE docker -H YOUR_SERVER_IP:2376 run --name -it -e SAMPLE_ENV=SAMPLE_ENV_VARIABLE -p 80:80 -d $YOUR_IMAGE
Honestly, this opens up so many options and enhances your reach on environments.
Risks and Side Effects
Take a moment the notice that the definition of the IP address we gave in the docker.service file.
0.0.0.0 means that any person who has the IP of your server and port of the Docker can connect to your Docker engine without hesitation. Opened ports are easily findable via various easy techniques thus your environment can be instantly vulnerable to attack. Take a look at this article about attacking exposing Docker API’s to have a grasp on the situation.
There are various solutions such as HTTP Basic Authentication with Nginx, adding a TLS client certificate verification to Docker API. Personally I came up with another solution. I’ll edit this part when I wrote the article about it.