我将展示一个不需要编写新 Dockerfile 的解决方案,您可以使用官方的 nginx 镜像。
与@Jimmy 的解决方案一样,我们将使用envsubst 命令替换shell 格式字符串中的环境变量。
此命令适用于 offical nginx image 和 alpine 版本。
第 1 步
将您的 nginx 配置写入模板文件 - 我们称之为:site.template:
server {
listen ${PORT};
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
注意 PORT 占位符。
第 2 步 - 使用 docker compose
将其挂载到/etc/nginx/conf.d 目录中,然后执行envsubst 命令将模板用作default.conf 的参考:
web:
image: nginx:alpine
volumes:
- ./site.template:/etc/nginx/conf.d/site.template
ports:
- "3000:8080"
environment:
- PORT=8080
command: /bin/sh -c "envsubst < /etc/nginx/conf.d/site.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"
请注意:
1. 之后需要执行 nginx 守护进程。
2. 我使用/bin/sh 而不是/bin/bash,因为我的基础镜像是 alpine。
第 2 步(另一个选项)- 内联 docker run
如果由于某种原因您不想使用 docker-compose,您可以使用以下 bash 脚本:
#!/usr/bin/env bash
##### Variables #####
PORT=8080 #Or $1 if you pass it from command line
TEMPLATE_DIR=$(pwd)/site.template
TEMPLATE_REMOTE_DIR=/etc/nginx/conf.d/site.template
IMAGE_NAME=nginx:alpine
echo "Starting nginx on port: $PORT ..."
##### The docker command #####
docker run -p 3000:$PORT -v $TEMPLATE_DIR:$TEMPLATE_REMOTE_DIR $IMAGE_NAME \
/bin/sh -c "envsubst < $TEMPLATE_REMOTE_DIR > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"