Skip to main content

Docker Tips

Any edit in a Dockerfile will cause re-builds of consequential steps, so put lines that rarely changes in front1


Avoid using COPY . to copy a whole folder, only copy files are needed to avoid rebuild when any file changes in the folder1


Too many RUN commands increase layers. Try to combine set steps into one.1


Don't install any development/debug tools/packages for production, only install everything that is needed. like using --no-install-recommends with apt1


remove package cache1


use official images when possible: using python3.7 instead of ubuntu when the image is for a python app.1


use more specific tags, which show the version explicitly; also specify the minimal image when possible, install everything manually1


  1. build from source in a consistent environment (use docker to build)
  2. fetch & install dependencies in a separate step
  3. use multi-stage builds to remove build dependencies 1

docker images can be manually moved to another host if both public and private registries aren't able to be used. 2 3

on source

docker save myimage:latest | gzip > myimage_latest.tar.gz

on destination

docker load < myimage_latest.tar.gz

Remove containers. containers can be removed automatically if --rm is used with docker run, we can use the follow command to erase them.4

docker container prune

we can stop and erase all containers as well

docker container stop $(docker container ls -aq)
docker container rm $(docker container ls -aq)

Get IP address of a container.5

Modern Docker

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id

Old Docker

docker inspect --format '{{ .NetworkSettings.IPAddress }}' container_name_or_id

customized function for shell6

Pop this into your ~/.bashrc (Linux) or ~/.bash_profile (Mac)

dockip() { 
docker inspect --format '{{ .NetworkSettings.IPAddress }}' "$@" }

Runnig docker as a non-root user7

A general pricipal is: build everything as usual, then switch to a non-root user to run the service.

before entrypoint

USER <username>

Footnotes

  1. 你确定你会写 Dockerfile 吗? - 米开朗基杨的博客, Zotero 2 3 4 5 6 7 8

  2. docker image save, Zotero

  3. docker image load, Zotero

  4. 小贴士:Docker清理作弊手册, Zotero

  5. How to get a Docker container's IP address from the host? - Stack Overflow, Zotero

  6. 10 Examples of how to get Docker Container IP Address

  7. Docker 容器内以非 root 用户运行, Zotero