如何构建一个自定义的基于 nginx:alpine 的容器,侦听 80 以外的端口?

Ric*_*des 4 containers http nginx docker alpine-linux

我需要一个基于 nginx:alpine 的 Docker 容器从端口 8080 提供 http 内容,但 nginx:alpine 默认监听端口 80。
构建自定义容器时如何更改端口?

Ric*_*des 9

选项 1(推荐):设置新的配置文件

使用以下内容创建本地default.conf*文件:

server {
    listen       8080;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
Run Code Online (Sandbox Code Playgroud)

* 超出8080端口,自定义以上内容,满足您的需求

default.conf复制到自定义容器 [Dockerfile]:

FROM nginx:alpine
## Copy a new configuration file setting listen port to 8080
COPY ./default.conf /etc/nginx/conf.d/
EXPOSE 8080
CMD ["nginx", "-g", "daemon off;"]
Run Code Online (Sandbox Code Playgroud)

选项 2:更改 nginx 默认配置 [Dockerfile]

FROM nginx:alpine
## Make a copy of default configuration file and change listen port to 8080
RUN cp /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.orig && \
    sed -i 's/listen[[:space:]]*80;/listen 8080;/g' /etc/nginx/conf.d/default.conf
EXPOSE 8080
CMD ["nginx", "-g", "daemon off;"]
Run Code Online (Sandbox Code Playgroud)

当然,备份原始配置是可选的