0%

Docker Cheat Sheet Notes

After trying Docker for a couple of days, I felt it was genuinely impressive. It immediately made me want to containerize everything I was running.

Docker was already extremely popular at that time, but it was still new enough that there was a lot to learn. Here are a few notes from issues I ran into while using it, collected as a personal cheat sheet.

How do I stop and remove all containers?

When testing Docker, it is easy to accumulate a lot of containers. Deleting them one by one is annoying, so these commands are useful:

1
2
docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)

detach and attach

If you start a container with docker run -d, it runs in the background. You can later bring it back to the foreground with docker attach.

After attaching, Ctrl+P followed by Ctrl+Q can detach without stopping the container.

A useful explanation from Stack Overflow:

1
2
3
docker run -t -i → can be detached with ^P^Q and reattached with docker attach
docker run -i → cannot be detached with ^P^Q; will disrupt stdin
docker run → cannot be detached with ^P^Q; can SIGKILL client; can reattach with docker attach

In practice, the behavior of attach depends quite a lot on whether -i and -t were used when starting the container.

Reference:

http://stackoverflow.com/questions/20145717/how-to-detach-from-a-docker-container

Use the host’s local timezone inside Docker

The timezone inside a container may differ from the host system. A simple workaround is to mount the host’s /etc/localtime into the container:

1
docker run --rm -t -i -v /etc/localtime:/etc/localtime:ro centos:centos6 date

Why does crontab not run inside Docker?

I found that even after installing crontabs in the official CentOS 6 image, cron jobs still would not run.

After stopping the crond service and starting it manually with crond -i, I found the following error in /var/log/cron:

FAILED to open PAM security session (Cannot make/remove an entry for the specified session)

One workaround suggested online is to edit /etc/pam.d/crond and change required to sufficient.

That worked in my test.

Move Docker’s storage directory

At that time Docker did not provide a clean built-in way to move image and runtime storage to another path. Everything lived under /var/lib/docker.

The usual workaround was to move the directory elsewhere and remap it. Some people suggested using a bind mount instead of a symlink to avoid odd problems:

1
mount -o bind /var/lib/docker /new/var/lib/docker
如果我的文字帮到了您,那么可不可以请我喝罐可乐?