【问题标题】:Create config file when running Docker container with Compose使用 Compose 运行 Docker 容器时创建配置文件
【发布时间】:2018-09-18 07:21:55
【问题描述】:

我有以下Dockerfile

FROM node:10.8.0-alpine as builder

# Set working directory
RUN mkdir /usr/src
RUN mkdir /usr/src/app
WORKDIR /usr/src/app

# Add /usr/src/app/node_modules/.bin to $PATH
ENV PATH /usr/src/app/node_modules/.bin:$PATH

# Get build arguments coming from .env file
ARG API_URL
ENV API_URL "$API_URL"

# Create config file from environment variables
RUN echo "API_URL = $API_URL" > ./app.cfg

# Install and cache app dependencies
COPY package.json /usr/src/app/package.json
RUN npm install
RUN npm install react-scripts@1.1.1 -g
COPY . /usr/src/app
RUN npm run build

# Production environment
FROM nginx:1.15.2-alpine
COPY --from=builder /usr/src/app/build /usr/share/nginx/html
CMD ["nginx", "-g", "daemon off;"]

我使用以下 docker-compose.yml 文件来构建我的 Docker 映像

version: '3'
services:

  app:
    container_name: data-quality-app
    restart: always
    image: data-quality-app
    build:
      context: ./app
      dockerfile: Dockerfile
      args:
        - API_URL=${API_URL}
    env_file:
      - ./.env
    ports:
      - 80:80
    networks:
      - default

networks:
  default:
    external:
      name: data-quality-network

volumes:
  data-quality-db-volume:
    external: true

注意文件.env包含环境变量API_URL=http://0.0.0.0:5433/graphql

这一切都很好,但是当我使用 Docker Compose 运行我的容器时:

$ docker-compose up app

我想覆盖容器中的文件app.cfg,以便用文件.env 中的当前值替换API_URL 的值。

我尝试在Dockerfile 中添加以下ENTRYPOINT,但没有成功:

[...]
# Create config file to from environment variables
RUN echo "API_URL = $API_URL" > ./app.cfg
ENTRYPOINT echo "API_URL = $API_URL" > ./app.cfg
[...]

我错过了什么?

【问题讨论】:

    标签: docker docker-compose environment-variables


    【解决方案1】:

    您应该编写一个执行所需设置的入口点脚本,然后运行传递给容器的命令。

    entrypoint.sh:

    #!/bin/sh
    if [ -n "$API_URL" ]; then
      echo "API_URL = $API_URL" > app.cfg
    fi
    exec "$@"
    

    Dockerfile(最后阶段):

    FROM nginx:1.15.2-alpine
    COPY entrypoint.sh /
    COPY --from=builder /usr/src/app/build /usr/share/nginx/html
    ENTRYPOINT ["/entrypoint.sh"]
    CMD ["nginx", "-g", "daemon off;"]
    

    你可以通过运行类似的东西来调试它

    docker build -t mynginx .
    docker run --rm -it -e API_URL=http://test mynginx sh
    

    它将运行入口点脚本,将“sh”作为命令传递给它;这将设置 app.cfg 文件,然后启动调试 shell(而不是 nginx)。

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多