docker 容器调试技巧

有时候docker容器可能因为映射不对,或者内部文件错误等等,会出现一启动就挂掉的情况,这种往往就是容器启动入口的程序有问题,但是因为一启动就挂,有时候日志啥的都看不到。这时候就可以通过 command 指令去覆盖掉默认Dockerfile 里面的 CMD 定义的入口(EntryPoint 定义的也类似)。

覆盖方式有两种

一种是 command: ["sleep","infinity"] 让主线程无限休眠,那么程序也就不会停止,那么docker 容器也就不会停掉。这样就可以通过 docker exec -it xxx bash 进入容器查看了。

另一个命令是 command: ["tail","-f","/dev/null"] 作用也是同理。

但是如果是用 docker swarm 或者 k8s 部署的调试的时候要注意, 因为这时候会有容器健康检测重启策略,用了上述命令,因为覆盖了默认的程序启动入口,那么健康检测逻辑就会失败,容器处于unhealthy 状态,然后就触发重启策略。

所以记得注释掉相关配置,如下示例:

version: "3.5"

services:
    nginx:
        hostname: nginx
        image: nginx
        ports:
            - target: 80
              published: 80
              mode: host
        deploy:
            mode: global
            # restart_policy:
            #     condition: on-failure
        networks:
            - overlay
        # 加此命令进行调试容器的时候,不要开启 healthcheck 和 restart_policy 策略,
        # 否则容器处于 unhealthy 状态,会不断重启
        command: ["sleep","infinity"]
        # healthcheck:
        #     test: bash /opt/nginx/check.sh
        #     interval: 20s
        #     timeout: 10s
        #     retries: 3
        logging:
            driver: "json-file"
            options:
                max-size: "2000k"
                max-file: "10"

posted @ 2024-07-23 11:54  DHclly  阅读(1)  评论(0编辑  收藏  举报