Skip to content

Docker 命令指南

Commands

  • Check Commands: docker stats --help
  • Run: docker run -it ubuntu /bin/bash
  • Check Container: docker ps -a
  • Start/Stop/Restart: docker start/stop/restart <container-id>
  • Check Images: docker images
  • Delete Container: docker rm -f <container-id>
  • Delete Image: docker rmi <img-name>
  • Pull or Update Image: docker pull <img>
  • Run Daemon: docker run -d -p 5000:5000 training/webapp python app.py
  • 查看端口:docker port <ID>
  • 查看日志:docker logs -f <ID>
  • 查看进程:docker top <name>
  • 查看信息:docker inspect <name>
  • mount: docker inspect <ID> | grep Source -A 1
  • 停止状态删除容器:docker rm <ID>
  • satrt container when stop and remove: docker run -it --rm [image] --bash
  • command: docker exec -it [contianer-id] /bin/bash or docker exec -it [cid] sh
  • start all containers with exited status: docker start $(docker ps -aq --filter "status=exited")
  • 命令参数:
    $ docker run -t -i ubuntu:15.10 /bin/bash
    
    # -i: 交互式操作。
    # -t: 终端。
    # ubuntu:15.10: 这是指用 ubuntu 15.10 版本镜像为基础来启动容器。
    # /bin/bash:放在镜像名后的是命令,这里我们希望有个交互式 Shell,因此用的是 /bin/bash。
    
  • Update Image:

    $ docker commit -m="has update" -a="runoob" e218edb10161 runoob/ubuntu:v2
    
    # -m: 提交的描述信息
    # -a: 指定镜像作者
    # e218edb10161:容器 ID
    # runoob/ubuntu:v2: 指定要创建的目标镜像名
    

  • Tag Image: docker tag <img-id> <repository name>:<tag>

Docker Compose

Step 1: setup

  1. create directory:
    $ mkdir emby
    $ cd emby
    
  2. create a file: app.py > redis is hostname of redis container on the application's work.

    import time
    
    import redis
    from flask import Flask
    
    app = Flask(__name__)
    cache = redis.Redis(host='redis', port=6379)
    
    def get_hit_count():
        retries = 5
        while True:
            try:
                return cache.incr('hits')
            except redis.exceptions.ConnectionError as exc:
                if retries == 0:
                    raise exc
                retries -= 1
                time.sleep(0.5)
    
    @app.route('/')
    def hello():
        count = get_hit_count()
        return 'Hello World! I have been seen {} times.\n'.format(count)
    
    3. create requirements.txt:
    flask
    redis
    

Step 2: Create Dockerfile

# syntax=docker/dockerfile:1
FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP=app.py
ENV FLASK_RUN_HOST=0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
EXPOSE 5000
COPY . .
CMD ["flask", "run"]

Step 3: Define services in a Compose file

new a docker-compose.yml

version: "3.9"
services:
  web:
    build: .
    ports:
      - "8000:5000"
  redis:
    image: "redis:alpine"

Step 4: Build and run with Compose

  1. From project directory, run docker-compose up
  2. Enter http://localhost:8000/ and see application running.
  3. Type: docker image ls to list local images. And inspect images with docker inspect <tag or id>
  4. Stop with docker-compose down.

Step 5: Edit Compose file and add a bind mount

add bind mount path for web service.

version: "3.9"
services:
  web:
    build: .
    ports:
      - "8000:5000"
    volumes:
      - .:/code
    environment:
      FLASK_ENV: development
  redis:
    image: "redis:alpine"

Step 6: Re-build and run the app

$ docker-compose up

Step 7: Update the application

Edit the app.py and Refresh.

Step 8: some commands

$ docker-compose up -d  # detached mode
$ docker-compose run web env  # see web environment variables.
$ docker-compose stop  # if started with -d
$ docker-compose down --volumes # remove the data volume.

Docker 加速

  • edit /etc/docker/daemon.json
{
  "registry-mirrors": [
    "https://hub-mirror.c.163.com",
    "https://mirror.baidubce.com"
  ]
}
  • restart
sudo systemctl daemon-reload
sudo systemctl restart docker
# check
docker info
  • remove images
    # remove None images
    docker images -q --filter "dangling=true" | xargs docker rmi
    

Add User to Docker

permission denied while trying to connect to the Docker daemon socket...

  1. sudo groupadd docker
  2. sudo usermod -aG docker $USER
  3. exit the session and login again.
  4. id -nG
  5. Else: sudo systemctl restart docker

Docker 命令

# 10 min 前 logs
docker logs --since 10m CONTAINER
# 1 hour 前
docker logs --since 1h CONTAINER
# since
docker logs --since 2023-04-13T09:20:00 <container_id>
# last 100 lines
docker logs -f --tail 100 CONTAINER
# to file
docker logs CONTAINER >& access.log
docker logs CONTAINER | grep "29/Mar/2022" >> access_tmp.log
docker logs CONTAINER 2>&1 | grep "29/Mar/2022" >& access_tmp.log

# stats
docker stats [OPTIONS] [CONTAINER...]
docker stats --no-stream
# top
docker top CONTAINER

docker pause CONTAINER [CONTAINER...]
docker unpause CONTAINER [CONTAINER...]
# tag
docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]
docker save busybox > busybox.tar
docker save --output busybox.tar busybox
docker load < busybox.tar
docker load -i busybox.tar
docker history [OPTIONS] IMAGE
# image
docker image prune
docker image prune -a
# 停止所有正在運行的 Container
docker container stop $(docker ps -q)
# 移除全部停止的 containers
docker container prune

Volume(卷)

# volume
docker volume ls [OPTIONS]
# 創造一個 volume
docker volume create [OPTIONS] [VOLUME]
# 刪除一個 volume
docker volume rm [OPTIONS] VOLUME [VOLUME...]
# 移除全部未使用的 volume
docker volume prune [OPTIONS]
  • 也可以建立 readonly 的 volumes (容器內 readonly)
version: '3.5'
services:
  nginx:
    image: nginx
    ports:
      - "80:80"
    volumes:
      - "nfs-data:/data:ro,z"

volumes:
    nfs-data:

Network

docker network ls [OPTIONS]
docker run -it --name busybox --rm --network=host busybox
# 建立 network
docker network create [OPTIONS] NETWORK
# 移除 network
docker network rm NETWORK [NETWORK...]
# 移除全部未使用的 network
docker network prune [OPTIONS]
# 查看 network 詳細資料
docker network inspect [OPTIONS] NETWORK [NETWORK...]
# 將 container 連接 network
docker network connect [OPTIONS] NETWORK CONTAINER
# 断开网络
docker network disconnect [OPTIONS] NETWORK CONTAINER