在容器内从 docker-compose 命令运行 shell 脚本

Kev*_*ith 10 linux docker docker-compose

我正在尝试通过在 docker 容器内使用 docker-compose 来运行 shell 脚本。我正在使用 Dockerfile 构建容器环境并安装所有依赖项。然后我将所有项目文件复制到容器中。据我所知,这很有效。(我对 docker、docker-compose 还是比较陌生的)

我的 Dockerfile:

FROM python:3.6-alpine3.7

RUN apk add --no-cache --update \
    python3 python3-dev gcc \
    gfortran musl-dev \
    libffi-dev openssl-dev

RUN pip install --upgrade pip

ENV PYTHONUNBUFFERED 1
ENV APP /app

RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
RUN mkdir $APP
WORKDIR $APP

ADD requirements.txt .
RUN pip install -r requirements.txt

COPY . .
Run Code Online (Sandbox Code Playgroud)

我目前正在尝试的是:

docker-compose 文件:

version: "2"

services:
  nginx:
    image: nginx:latest
    container_name: nginx
    ports:
      - "8000:8000"
      - "443:443"
    volumes:
      - ./:/app
      - ./config/nginx:/etc/nginx/conf.d
      - ./config/nginx/ssl/certs:/etc/ssl/certs
      - ./config/nginx/ssl/private:/etc/ssl/private
    depends_on:
      - api
  api:
    build: .
    container_name: app
    command: /bin/sh -c "entrypoint.sh"
    expose:
      - "5000"
Run Code Online (Sandbox Code Playgroud)

这导致容器无法启动,从日志中我得到以下信息:

/bin/sh: 1: entrypoint.sh: not found
Run Code Online (Sandbox Code Playgroud)

有关更多参考和信息,这是我的 entrypoint.sh 脚本:

python manage.py db init
python manage.py db migrate --message 'initial database migration'
python manage.py db upgrade
gunicorn -w 1 -b 0.0.0.0:5000 manage:app
Run Code Online (Sandbox Code Playgroud)

基本上,我知道我可以在 dockerfile 的命令行中仅使用上面的 gunicorn 行来运行容器。但是,我在应用程序容器中使用了一个 sqlite db,并且确实需要为数据库运行 db 命令来初始化/迁移。

仅供参考,这是一个基本的 Flask python web 应用程序,带有使用 gunicorn 的 nginx 反向代理。

任何见解将不胜感激。谢谢。

Adi*_*iii 13

第一件事,您正在复制您从构建参数传递entrypoint.sh到的内容$APP,但您没有提到这一点,第二件事您需要为entrypoint.sh. 最好添加这三行,这样您就不需要command在 docker-compose 文件中添加。

FROM python:3.6-alpine3.7
RUN apk add --no-cache --update \
    python3 python3-dev gcc \
    gfortran musl-dev \
    libffi-dev openssl-dev
RUN pip install --upgrade pip
ENV PYTHONUNBUFFERED 1
ENV APP /app
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
RUN mkdir $APP
WORKDIR $APP
ADD requirements.txt .
RUN pip install -r requirements.txt

COPY . .
# These line for /entrypoint.sh
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
entrypoint "/entrypoint.sh"
Run Code Online (Sandbox Code Playgroud)

docker compose for api 将是

  api:
    build: .
    container_name: app
    expose:
      - "5000"
Run Code Online (Sandbox Code Playgroud)

或者你可以使用你自己的也可以正常工作

version: "2"

services:
  api:
    build: .
    container_name: app
    command: /bin/sh -c "entrypoint.sh"
    expose:
      - "5000"
Run Code Online (Sandbox Code Playgroud)

现在您也可以使用 docker run 命令进行检查。

docker run -it --rm myapp

Run Code Online (Sandbox Code Playgroud)