首页 > 解决方案 > docker-compose:为什么在这里调用我的 python 应用程序?

问题描述

我一直在为此挠头。我的 python 应用程序有以下 Dockerfile:

# Use an official Python runtime as a parent image
FROM frankwolf/rpi-python3

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app
RUN chmod 777 docker-entrypoint.sh

# Install any needed packages specified in requirements.txt
RUN pip3 install --trusted-host pypi.python.org -r requirements.txt

# Run __main__.py when the container launches
CMD ["sudo", "python3", "__main__.py", "-debug"] # Not sure if I need sudo here

码头工人撰写文件:

version: "3"

services:
    mongoDB:
        restart: unless-stopped
        volumes:
            - "/data/db:/data/db"
        ports:
            - "27017:27017"
            - "28017:28017"
        image: "andresvidal/rpi3-mongodb3:latest"
    mosquitto:
        restart: unless-stopped
        ports:
            - "1883:1883"
        image: "mjenz/rpi-mosquitto"
    FG:
        privileged: true
        network_mode: "host"
        depends_on:
            - "mosquitto"
            - "mongoDB"
        volumes:
            - "/home/pi:/home/pi"
        #image: "arkfreestyle/fg:v1.8"
        image: "test:latest"
        entrypoint: /app/docker-entrypoint.sh
        restart: unless-stopped

这就是 docker-entrypoint.sh 的样子:

#!/bin/sh
if [ ! -f /home/pi/.initialized ]; then
    echo "Initializing..."
    echo "Creating .initialized"
    # Create .initialized hidden file
    touch /home/pi/.initialized

else
    echo "Initialized already!"
    sudo python3 __main__.py -debug
fi

这是我想做的事情:

(这东西已经有效了)

1)当我在容器中运行我的python应用程序时,我需要一个运行我的python应用程序的docker镜像。(这有效)

2)我需要一个运行2个服务+我的python应用程序的docker-compose文件,但是在运行我的python应用程序之前我需要做一些初始化工作,为此我创建了一个shell脚本,它是docker-entrypoint.sh。当我第一次在机器上部署我的应用程序时,我只想做一次初始化工作。所以我正在创建一个 .initialized 隐藏文件,我用它来检查我的 shell 脚本。

我读到在 docker-compose 文件中使用入口点会覆盖给 Dockerfile 的任何旧入口点/cmd。这就是为什么在我的 shell 脚本的 else 部分中,我使用“sudo python3 main .py -debug”手动运行我的代码,这个 else 部分工作正常。

(这是主要问题)

在 if 部分,我不在 shell 脚本中运行我的应用程序。我已经单独测试了 shell 脚本本身,if 和 else 语句都按我的预期工作,但是当我运行“sudo docker-compose up”时,当我的 shell 脚本第一次遇到 if 部分时,它会回显这两个语句,创建隐藏文件,然后运行我的应用程序。应用程序的控制台输出显示为紫色/粉红色/淡紫色,而其他两个服务以黄色和青色打印它们的日志。我不确定颜色是否重要,但在正常情况下,我的应用程序日志始终是绿色的,实际上前两个回显“Initializing”和“Creating .initialized”也是绿色的!所以我想我会提到这个细节。在这两个回声之后,

为什么/如何在 shell 脚本的 if 语句中调用我的应用程序?

(这仅在我通过 docker-compose 运行时发生,而不是在我仅使用 sh docker-entrypoint.sh 运行 shell 脚本时发生)

标签: pythonbashshelldockerdocker-compose

解决方案


问题 1

使用ENTRYPOINTandCMD同时有一些奇怪的效果

问题 2

这发生在您的容器上:

  1. 它是第一次启动。该.initialized文件不存在。
  2. 案件if被执行。文件已创建。
  3. 脚本和容器结束。
  4. restart: unless-stopped选项重新启动容器。
  5. .initialized文件现在存在,else案例正在运行。
  6. python3 __main__.py -debug被执行。

顺便说一句,USERDockerfile 中的命令或userDocker Compose 中的选项比sudo.


推荐阅读