我们使用docker images查看镜像,发现 node:alpine 体积是 nginx:alpine 的数倍大小。
    image.png
    下面我们使用nginx镜像来部署我们的应用

    简单的操作
    进入nginx

    1. docker run -it --rm nginx:alpine sh
    2. # 进入容器中,在容器中可通过 exit 退出容器环境
    3. $ exit

    默认配置文件位于 /etc/nginx/conf.d/default.conf,通过 cat 可查看配置。

    1. # 该命令在 nginx 的容器中执行
    2. $ cat /etc/nginx/conf.d/default.conf

    访问 nginx 的默认页面

    1. # -p 3000:80,在本地 3000 端口访问 nginx 页面
    2. $ docker run -it --rm -p 3000:80 nginx:alpine

    image.png

    打开conf文件,配置一下内容

    1. server {
    2. listen 80;
    3. server_name localhost;
    4. location / {
    5. root /usr/share/nginx/html;
    6. index index.html index.htm;
    7. }
    8. error_page 500 502 503 504 /50x.html;
    9. location = /50x.html {
    10. root /usr/share/nginx/html;
    11. }
    12. }

    该配置文件做了以下两个事情。

    1. 监听本地 80 端口
    2. 为 /usr/share/nginx/html 目录做静态资源服务

    写一个 Dockerfile 将我们的示例项目跑起来,仅仅需要两行代码。由于 nginx 镜像会默认将 80 端口暴露出来,因此我们无需再暴露端口。

    1. FROM nginx:alpine
    2. ADD index.html /usr/share/nginx/html/

    继续完成 docker-compose.yaml,并创建容器。

    1. version: "3"
    2. services:
    3. nginx-app:
    4. build:
    5. context: .
    6. dockerfile: nginx.Dockerfile
    7. ports:
    8. - 4000:80

    启动

    1. $ docker-compose up --build

    此时,访问 http://localhost:4000 即可访问成功。在控制台查看响应头,可发现有: Server: nginx/1.23.1。
    image.png

    通过 docker-compose 同时将基于 node/nginx 镜像构建容器

    1. version: "3"
    2. services:
    3. node-app:
    4. build:
    5. context: .
    6. dockerfile: node.Dockerfile
    7. ports:
    8. - 3000:3000
    9. nginx-app:
    10. build:
    11. context: .
    12. dockerfile: nginx.Dockerfile
    13. ports:
    14. - 4000:80

    这时候3000和4000端口都可以访问了,相当于部署了两个应用了

    在本地使用 nginx 镜像并挂载 nginx 配置启动容器
    image.png
    常用配置:

    1. 如何配置静态资源缓存策略
    2. 如何配置 CORS
    3. 如何配置 gzip/brotli 配置
    4. 如何配置路由匹配 Location
    5. 如何配置 Rewrite、Redirect 等

    我们将注意力集中在静态资源nginx配置两个点,在本地进行更新及维护,并通过 Volume 的方式挂载到 nginx 容器中。

    1. # 通过此配置可在 Docker 环境中学习 nginx 的各种指令
    2. # # 如果需要修改配置,验证配置是否生效,可通过 docker-compose 重新启动该容器 (或者 npm run learn:nginx)
    3. version: "3"
    4. services:
    5. learn-nginx:
    6. image: nginx:alpine
    7. ports:
    8. - 4000:80
    9. volumes:
    10. - ./nginx.conf:/etc/nginx/conf.d/default.conf
    11. - .:/usr/share/nginx/html

    配置nginx.conf

    1. server {
    2. listen 80;
    3. server_name localhost;
    4. root /usr/share/nginx/html;
    5. index index.html index.htm;
    6. location / {
    7. expires -1;
    8. # 此时通过 docker-compose 打开地址,可发现添加了一个新的 X-Hello 响应头
    9. add_header X-Hello xiumubai;
    10. }
    11. }

    启动容器

    1. docker-compose -f volumes.docker-compose.yaml up learn-nginx

    打开http://localhost:4000,多了个相应头X-Hello
    image.png