logo
blog
readme
Back to Blog
Back to Blog
Back to Blog

‌

‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌
‌

© 2025 linzhe. All rights reserved.

TODO:编辑

使用 docker 部署 nginx 应用

案例源码

1、使用dockerfile制作镜像

webapp

dockerfile:webapp

dockerfile
Dockerfile
FROM nginx
# nginx配置
COPY ./nginx/webapp.conf /etc/nginx/conf.d/webapp.conf
# 这个www目录就是当前打包出来的应用(一个普通的vue3应用)
COPY ./www /usr/share/nginx/html
#! 用于向用户和其他开发人员传达容器内应用程序所监听的端口。
#! 它本身并不会在构建或运行镜像时触发任何动作。
#! EXPOSE 仅仅是一个元数据,用于提供关于容器的信息
# EXPOSE 4534

webapp.conf

nginx
webapp.conf
server {
  listen       4534;
  server_name  localhost;

  location / {
    # 可以使用数据卷共享
    root   /usr/share/nginx/html;
    index  index.html index.htm;
  }
  # 测试反向代理
  location /api {
    # webserver 表示一个容器
    proxy_pass http://webserver:3000;
  }
}

webserver

index.js

js
index.js
const express = require('express')
const app = express()
const port = 3000

app.get('/api/list', (req, res) => {
  res.send({
    success: true,
    data: [
      { name: 'vue', value: 1 },
      { name: 'react', value: 2 },
      { name: 'ng', value: 3 },
      { name: 'express', value: 4 },
      { name: 'nestjs', value: 5 },
    ],
    msg: '',
  })
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

dockerfile:webserver

dockerfile
Dockerfile
FROM node:16
WORKDIR /app
COPY . .
RUN npm install
CMD ["npm", "start"]

2、使用dockder compose管理容器

yml
docker-compose.yml
version: '3'
services:
  webapp:
    build: ./webapp # 根据指定目录下的Dockerfile构建镜像
    # links: # links指令已被弃用
    #   - webserver # 允许一个容器能够访问另一个容器,并在它们之间建立网络连接

    # 来指定服务webapp依赖于webserver服务。这样在启动时,
    # Docker Compose会确保先启动webserver服务,然后再启动webapp服务
    depends_on:
      - webserver
    ports:
      - '4534:4534'
  webserver:
    build: ./webserver # 根据指定目录下的Dockerfile构建镜像
    expose:
      - '3000' # 暴露容器给依赖当前容器的容器使用
  • 步骤 1:docker-compose build(第一次启动容器前需要)构建镜像
  • 步骤 2:docker-compose up -d后台启动容器