Millet Porridge

English version of https://corvo.myseu.cn

0%

Docker Series 2: Advanced

Volume

When we want to mount a volume inside a container, there are several scenarios:

  1. common config files
  2. some logs we want to keep in host
  3. database directory
  4. other black magic, like socket, or pid file

You may notice that when a container is stopped, the volume strategy will allow us to run a container to do the same thing in the same environment.

There is the official document on Docker volumes:

1
2
3
4
5
# Mount local /tmp dirctory to contaier /home/corvo/tmp
docker run -ti \
-v /tmp:/home/corvo/tmp \
debian\
/bin/bash

You need not worry about the directory not existing; Docker will create it for you.

Port forwarding

Docker Networking overview

There are some methods to let the container listen on a port on the host. Port forwarding is one of them. When we create a new container and want to forward port 80 in the container to 10080 on the host, we can use the following command:

1
2
3
4
5
6
7
8
9
$ docker run \
-ti -p 10080:80 \
my_image \
python -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...

$ netstat -tnlp
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp6 0 0 :::10080 :::* LISTEN -

Host network and process

Docker run reference

I’d like to introduce the -net host, -pid host in this section.

-net host will share the host’s network stack and all interfaces from the host will be available to the container. You can use 127.0.0.1 to access the service in the host.

--pid host will use the host’s PID namespace inside the container. It means you can use ps -aux to display all process in the host.

These two arguments give the container the ability to communicate with the host machine. It’s powerful, but prone to some security issues. Once a hacker enters the container, he or she could manipulate the whole machine.

A simple server should never use these functions. There are several scenarios where we need them, and I will give examples later in other blogs.

Restart policies

Restart policies

This flag will tell the docker daemon how the container should or should not be restarted on exit.

Docker supports the following restart policies: no, on-failure[:max-retries], always, unless-stopped.

I prefer to use unless-stopped. This policy will ensure that the container is running even if I restart the docker daemon or the machine, which makes docker very useful in development.