Docker Memo

Docker 备忘。

Docker CMD

base command

1
2
3
4
5
$ docker stop $(docker ps -a -q);
$ docker logs -f <contaner name> &> yourlog.log &
$ docker cp <container_id>:source_path destination_path
$ sudo su
$ chmod -R 777 /path

logs

1
2
$ docker logs --since=2m <container_id> // since last 2 minutes
$ docker logs -f --tail 10 <container_name>

entrypoint VS. cmd

  • 至少指定一个
  • 容器作为可执行文件时应该定义 ENTRYPOINT
  • CMD 应该用作定义 ENTRYPOINT 命令,或在容器中执行 ad-hoc 命令的默认参数的一种方式
  • 使用替代参数运行容器时,CMD 将被覆盖
  • 默认的entrypoint是/bin/sh -c

expose VS. publish

  • EXPOSE 是暴露端口,主要用在 Dockerfile 中,-publish 是映射端口,主要用在 run 时
  • 都没有时,容器里的服务只能在里面访问
  • 只有 EXPOSE 时,容器外部无法访问,但其他容器内部可以访问,有利于容器间通信
  • 只有 -p 时,容器外部可以访问,同时会自动 EXPOSE

timezone

1
2
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

remove

1
2
3
$ docker rmi $(docker images --filter "dangling=true" -q --no-trunc)
$ docker images | grep none | awk '{ print $3; }' | xargs docker rmi
$ docker image prune --filter="dangling=true"

host

docker run 时使用 --net="host" 后,容器内的 localhost 就是 Docker 的 host。Mac 下可以使用 host.docker.internal

enviroment

Dockerfile:

1
2
ARG TOKEN=${TOKEN:-""}
ENV TOKEN=${TOKEN}

构建命令:

1
2
3
4
# TOKEN 是环境变量,echo $TOKEN 应显示对应的 token
docker build --build-arg TOKEN -t name:latest .
# 或者
docker build --build-arg TOKEN=<"your_token"> -t name:latest .

这样,TOKEN 这个变量就会传到容器内部,作为环境变量。或者在运行时添加 -e 参数:

1
docker run -e TOKEN name

这种情况下,TOKEN 变量也会传到容器内部。

在 Dockerfile 中定义 build 时指定,适用于比较固定的环境变量(比如 Token,Host);运行时传入,适用于需要动态变化的环境变量(比如 PROFILE)。

这两种用法也适用于 docker-compose(build 和 run)。

export VS. save

  • save 包含所有父层级和版本,export 只有当前容器。
1
2
3
4
5
docker export -o export.tar container_id
docker save -o save.tar image_id

docker import export.tar repository:tag
docker load < save.tar

proxy

1
2
docker build --build-arg HTTP_PROXY="http://proxy.example.com:3128" .
docker run --env HTTP_PROXY="http://proxy.example.com:3128" redis

Net

1
2
3
4
5
6
7
8
9
# Access iptables
docker run --cap-add=NET_ADMIN -it ubuntu:16.04
# In the container
apt update -y
apt-get install iptables sudo -y
adduser user1
adduser user1 sudo
su - user1
sudo iptables -L -n

Reference