How to start a docker container as daemon process

Instead of running docker container with an interactive shell it is also possible to let docker container to run as a daemon which means that the docker container would run in the background completely detached from your current shell. The following CentOS docker container will start as a daemonized container using -d option, while at the same time executing ping 8.8.8.8 using an endless bash while loop.

# docker run --name centos-linux -d centos /bin/sh -c "while true; do ping 8.8.8.8; done"

Using docker’s ps command we see the that our centos-linux container is running:

# docker ps
CONTAINER ID IMAGE        COMMAND         CREATED       STATUS       PORTS        NAMES
6acfc613c604 centos:7     "/bin/sh -c 'while t 23 seconds ago   Up 23 seconds                    centos-linux

The actual output from the above endless while loop can be access by examining container logs:

# docker logs 6acfc613c604
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=56 time=18.5 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=56 time=18.8 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=56 time=18.1 ms

Use docker exec to reattach to your container interactive shell:



# docker exec -it centos-linux /bin/bash
[root@6acfc613c604 /]#

Furthermore, using docker exec we can also run any desired command within the docker container. The below command will use docker exec to obtain in IP address assigned to centos-linux container without the need for an interactive shell:

# docker exec -it centos-linux ip add show 
1: lo:  mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
67: eth0:  mtu 1500 qdisc noqueue state UP 
    link/ether 02:42:ac:11:00:21 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.33/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:acff:fe11:21/64 scope link 
       valid_lft forever preferred_lft forever

To stop daemonized container is the same as to stop any other docker container:

# docker stop 6acfc613c604
6acfc613c604