docker + nginx 实战练习总结

302 阅读2分钟

应用练习

目录结构

  1. frontend

    这是前端工程所处的目录,内部dist目录下就是前端的打包后的资源

  2. backend

    这是后台node程序,一般运行node程序,不会直接去运行,而是通过PM2这样一个进程守护的程序去运行node程序

    • process.yml

      去描述它的运行
      apps:
          # 启动执行的文件,我们这个node程序启动是node app.js,所以就是app.js
        - script : server.js
          # 启动 2个 进程
          instances: 2
           # 对代码启用一个监听状态
          watch  : true
          # node 中的 env 设置为 生产模式
          env    :
            NODE_ENV: production
      
    • .dockerignore

      node_modules
      
    • Dockerfile

      # 告诉docker我们是从哪个镜像开始往下写
      FROM keymetrics/pm2:latest-alpine
      # 把 当前目录 添加到宿主机的 /usr/src/app 目录下,copy过去
      ADD . /usr/src/app
      # 相当于cd命令, 进入这个目录
      WORKDIR /usr/src/app
      # 定制镜像的过程中运行的内容
      RUN npm config set registry https://registry.npm.taobao.org/ && \  
          npm i
      # 对外暴露的端口
      EXPOSE 3000
      # docker run 的时候执行的指令, 直接理解为:程序启动脚本
      # pm2在docker中使用命令为pm2-docker
      # CMD ["pm2-runtime", "start", "--json", "process.json"]
      CMD ["pm2-runtime", "start",  "process.yml"]
      
  3. nginx

    Nginx 服务配置文件,内部定义 监听端口,静态资源,反向代理等配置

    • 创建conf.d目录,内部再创建一个nginx.conf文件

      server {
          listen       80;
      ​
          location / {
              root   /var/www/html;
              index  index.html index.htm;
          }
      ​
          location ~ .(gif|jpg|png)$ {
              root /static;
              index index.html index.htm;
          }
      ​
      ​
          location /vue {
                  proxy_pass  http://app-pm2:3000;
                  proxy_redirect     off;
                  proxy_set_header   Host             $host;
                  proxy_set_header   X-Real-IP        $remote_addr;
                  proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
          }
      }
      
  4. docker-compose.yml

    docker总配置入口,运行也是根据此文件配置来start

    version: '3.1'
    services:
      app-pm2:
        container_name: app-pm2
        # 构建容器
        build: ./backend
        # 直接从git拉去
        # build: git@github.com:**/docker_ci.git#:backend
        # 需要链接本地代码时
        # volumes:
        #   - ./backend:/usr/src/app
        ports:
          - "3000:3000"
      mongo:
        image: mongo
        restart: always
        ports:
          - 27017:27017
      nginx:
        restart: always
        image: nginx
        ports:
          - 8081:80
        volumes:
          - ./nginx/conf.d/:/etc/nginx/conf.d
          # 将frontend/dist目录映射到/var/www/html目录上,这个路径就是nginx.conf文件中定义的路径
          - ./frontend/dist:/var/www/html/
          - ./static/:/static/
    
  5. webhooks

    配置webhooks,同github上公共工作,用来做CI持续集成

    var http = require('http')
    // 这个包就是用来监听git仓库的操作的,我们一般在git界面setting-> webhooks中配置只响应push操作
    var createHandler = require('github-webhook-handler')
    var handler = createHandler({ path: '/webhooks', secret: 'charphSecret' })
    // 上面的 secret 保持和 GitHub 后台设置的一致function run_cmd(cmd, args, callback) {
      var spawn = require('child_process').spawn
      var child = spawn(cmd, args)
      var resp = ''
    ​
      child.stdout.on('data', function (buffer) {
        resp += buffer.toString()
      })
      child.stdout.on('end', function () {
        callback(resp)
      })
    }
    ​
    http
      .createServer(function (req, res) {
        handler(req, res, function (err) {
          res.statusCode = 404
          res.end('no such location')
        })
      })
      .listen(7777, () => {
        console.log('WebHooks Listern at 7777')
      })
    ​
    handler.on('error', function (err) {
      console.error('Error:', err.message)
    })
    ​
    handler.on('*', function (event) {
      console.log('Received *', event.payload.action)
      //   run_cmd('sh', ['./deploy-dev.sh'], function(text){ console.log(text) });
    })
    ​
    handler.on('push', function (event) {
      console.log(
        'Received a push event for %s to %s',
        event.payload.repository.name,
        event.payload.ref
      )
      // 分支判断
      if (event.payload.ref === 'refs/heads/master') {
        console.log('deploy master..')
        run_cmd('sh', ['./deploy-dev.sh'], function (text) {
          console.log(text)
        })
      }
    })
    

    webhooks中调用的sh文件,内部用来做git更新 和 docker的 重启

    # deploy-dev.shecho Deploy Project
    ​
    # 获取最新版代码
    git pull
    ​
    # 强制重新编译容器
    docker-compose down
    docker-compose up -d --force-recreate --build