在 docker-compose.yml 文件中,command 指令会覆盖容器的默认命令(entrypoint)。但需要注意的是,这并不影响容器的入口点(entrypoint),而只会替代默认的命令部分。

  • entrypoint: 容器启动时执行的主命令。
  • command: 传递给 entrypoint 的参数,或者在没有自定义 entrypoint 时,作为容器的主命令执行。
version: '3'
services:
  app:
    image: myapp:latest
    entrypoint: ["python", "app.py"]  # 自定义入口点
    command: ["--arg1", "value1"]     # 替代默认命令

在这个例子中,容器启动时会执行:

python app.py --arg1 value1

如果想覆盖 entrypoint,需要使用 entrypoint 指令

command 的应用:

  1. nginx 添加登录验证
services:
  nginx:
    image: nginx:latest
    ports:
      - "8080:8080"  # nginx 容器的端口
    environment:
      - NGINX_USER=your_username     # 用户名
      - NGINX_PASSWORD=your_password # 密码
    command: >
      /bin/sh -c '
      apt-get update && apt-get install -y apache2-utils;
      echo "[nginx] starting with basic auth";
      htpasswd -cb /etc/nginx/.htpasswd $${NGINX_USER} $${NGINX_PASSWORD};
      echo "server {
          listen 8080;
          location / {
              proxy_pass http://app:5000;
              auth_basic \"Restricted Content\";
              auth_basic_user_file /etc/nginx/.htpasswd;
          }
      }" > /etc/nginx/conf.d/default.conf;
      nginx -g "daemon off;"'
  1. 镜像安装依赖

假设 Dockerfile

# Dockerfile
FROM python:3.9-slim
# Dockerfile 中的 command 指令,用户在运行容器时可以选择覆盖它
# 如果执行 docker run <your_image> <some_other_command>
# 则 <some_other_command> 会覆盖 CMD 指令中的命令,但不会影响 ENTRYPOINT 指令(如果有的话)
CMD ["tail", "-f", "/dev/null"] 

使用 command 安装所缺的依赖

version: "3.8"
services:
  app_python:
    image: 192.168.0.114:8039/python:3.9-slim-v20241127
    container_name: app_python
    restart: always
    #ports:
    #  - 4444:4444
    user: 0:0 # 使用 root 用户
    volumes:
      - ${WEB_ROOT}/app_python:/app
    environment:
      TZ: Asia/Shanghai
    command:
      /bin/bash -c 'pip3 install requests && tail -f /dev/null'