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 serveral scenes:

  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 do the same thing in the same environment.

There is the offical document in Docker volume:

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 may not worry about the directory not exist, Docker will create it for you.

Port forwarding

Docker Networking overview

There are some methods to let the container to listen to a port in the host. Port forwarding is one of them. when we create a new container, and we want to forward 80 in container to 10080 in 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 ability that container could communicate with the host machine. It’s powerful, but prone to some security issues. Once the hacker enter 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 daemeon 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 runing even if I restart the docker daemon or the machine, which makes docker very useful in development.