Damn I Love Docker: Miscellaneous Docker Tips
Table of Contents
Introduction
While there have been many posts written on this blog discussing the various applications of Docker, there is need to actually discuss some of the “finer” aspects of using docker. In this post we will introduce, and discuss some of the “lesser known” options, commands, and features related to Docker.
Sync Container and Host Time
This is the best way I have found to sync the time between host and container (for logging purposes):1
-v /etc/localtime:/etc/localtime:ro
Simply mount the volume for your /etc/localtime
into the container. This will
ensure that both the host machine running the Docker Engine and the
containers that will be run by the engine all have the same time.
Container Restart Policy
After enough time working with docker, experimenting with different options and
commands, and even running important applications in docker, you will eventually
want to know how to “restart” a container automatically. This is all handled
with the --restart
option.2
For example, I run a dockerized OpenVPN server on my home network, and I
want to make sure that it is ALWAYS RUNNING. This makes sense, because I may
be in situations where I need to access the VPN, but due to a power failure at some
point, the server has been restarted. Without the --restart
option set the
container running my VPN is not automatically restarted … This would be a
serious pain in the &$$, if you catch my drift. But with the --restart
option, this can be alleviated like so:
docker create --restart=always --name=ovpn -v /etc/localtime:/etc/localtime:ro -v $OVPN_DATA:/etc/openvpn -p 1194:1194/udp --cap-add=NET_ADMIN tigerj/rpi-ovpn
To clarify, the above command comes from a previous tutorial on docker
OpenVPN3, and if you look towards the beginning of the command you will see
the --restart=always
option. As you could imagine, this ensures that your
container will (per the documentation): “Always restart the container if it
stops.” Again, check out the reference2 if you would like to know more
details or other restart policies.
envsubst
The envsubst
command is a tool4 that will parse a file and search for
shell
variables to replace with their corresponding environment variable
values and then print the original file with the variable values substituted.
Below is an example NGINX
reverse proxy configuration:
$ cat reverse_proxy.tmpl
server {
listen ${LISTEN_PORT};
listen [::]:${LISTEN_PORT};
server_name ${SERVNAME};
location / {
proxy_pass ${DOMAIN}:${DOMAIN_PORT};
}
}
If we set the shell
values as follows:
$ LISTEN_PORT=80; SERVNAME=yourdomain.com; DOMAIN=localhost; DOMAIN_PORT=5000
And then run envsubst
$ envsubst < reverse_proxy.tmpl > reverse_proxy.conf
Then we will have a config file with our variables:
$ cat reverse_proxy.conf
server {
listen 80;
listen [::]:80;
server_name yourdomain.com;
location / {
proxy_pass localhost:5000;
}
}