作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个看起来像这样的 docker-compose,部分是:
nginx:
container_name: ${NGINX_CONTAINER_NAME}
ports:
- ${NGINX_HTTP_PORT1}:${NGINX_HTTP_PORT2}
- ${NGINX_HTTPS_PORT1}:${NGINX_HTTPS_PORT2}
build:
dockerfile: Dockerfile
args:
- NGINX_VERSION=${NGINX_VERSION}
volumes:
- ${NGINX_CONF_DIR:-./nginx}:/etc/nginx/conf.d
- ${NGINX_LOG_DIR:-./logs/nginx}:/var/log/nginx
- ${WORDPRESS_DATA_DIR:-./wordpress}:/var/www/html
depends_on:
- wordpress
restart: always
如您所见,我正在尝试将一个名为 NGINX_VERSION 的变量传递到 Dockerfile 中。
这是 .env 的内容:
# nginx
NGINX_VERSION=1.21.3
NGINX_HTTP_PORT1=8085
NGINX_HTTP_PORT2=8085
NGINX_HTTPS_PORT1=443
NGINX_HTTPS_PORT2=443
NGINX_CONTAINER_NAME=dev_nginx
这就是工作的 Dockerfile 的样子:
FROM nginx:1.21.3
RUN apt-get update \
&& apt-get -y install openssl \
&& apt-get -y install vim
RUN mkdir -p /etc/openssl/certs
RUN mkdir -p /etc/nginx/snippets
RUN openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/openssl/nginx-selfsigned.key -out /etc/openssl/nginx-selfsigned.crt -subj "/C=US/ST=NY/L=NY/O=ACME/OU=CD/CN=WPDeveloper"
问题
当我将 Dockerfile 中的图像名称更改为如下所示时:
FROM nginx:$NGINX_VERSION
或者这个:
FROM nginx:${NGINX_VERSION}
我收到以下错误:
failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to create LLB definition: failed to parse stage name "nginx:": invalid reference format
当我将版本号硬编码在 Dockerfile 中时,一切正常。此外,如果有帮助,我会通过运行以下命令来验证是否正在读取 env 中的值:
docker-compose -f .\docker-compose.yml config
在某种程度上,这就是输出的样子——注意它为 NGINX VERSION 找到了正确的值
nginx:
build:
dockerfile: Dockerfile
args:
NGINX_VERSION: 1.21.3
container_name: dev_nginx
depends_on:
wordpress:
condition: service_started
networks:
default: null
ports:
- mode: ingress
target: 8085
published: 8085
- mode: ingress
target: 443
published: 443
protocol: tcp
restart: always
volumes:
source: ./nginx
target: /etc/nginx/conf.d
bind:
create_host_path: true
- type: bind
source: ./logs/nginx
target: /var/log/nginx
bind:
create_host_path: true
- type: bind
source: ./wordpress
target: /var/www/html
bind:
create_host_path: true
如有任何提示,我们将不胜感激。
最佳答案
如果您希望您的 docker-compose 文件从 .env 文件中读取变量,然后将其传递给 Dockerfile,您可以按照以下设置进行操作:
这是您的 .env 文件包含的内容:
# nginx
NGINX_VERSION=1.21.3
这可以是您的 Dockerfile:
ARG NGINX_VERSION
FROM nginx:${NGINX_VERSION}
...
最后这将是您的 docker-compose.yml 文件:
nginx:
build:
context: .
dockerfile: Dockerfile
args:
NGINX_VERSION: ${NGINX_VERSION}
...
最后运行:
docker-compose up
确保您的 .env 文件与 Dockerfile 和 docker-compose.yml 文件位于同一目录中。
关于docker-compose - 如何将 env 变量从 .env 传递到 Dockerfile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69744407/
我是一名优秀的程序员,十分优秀!