通用 - hash模式 Dockerfile

  1. FROM node:9 as builder
  2. ARG ENV=development
  3. # http-server 不变动也可以利用缓存
  4. WORKDIR /code
  5. ADD package.json /code
  6. ADD package-lock.json /code
  7. ADD .npmrc /code
  8. RUN npm set strict-ssl false
  9. RUN npm install
  10. RUN npm install pm2 -g
  11. ADD . /code
  12. RUN npm run "build:${ENV}"
  13. # 选择更小体积的基础镜像
  14. FROM nginx:alpine
  15. COPY nginx.conf /etc/nginx/conf.d/nginx.conf
  16. COPY --from=builder /code/dist /usr/share/nginx/html
  17. EXPOSE 80

history模式 反向代理和静态资源缓存的问题

我们是在另外一台主机上配置nginx,这台机器我们暂且称为base001,然后通过反向代理跳到目标机器上。

刚开始在配置Nginx的base机器上面这样配置,发现无效

  1. location / {
  2. try_files $uri $uri/ /index.html;
  3. }

转而在dockerfile中修改nginx镜像的配置文件,还是没用。

在dockerfile中起一个Node应用,在这里配置history,见下面的app.js

  1. var express = require('express');
  2. var history = require('connect-history-api-fallback');
  3. var morgan = require('morgan');
  4. var mime = require('mime-types')
  5. var app = express();
  6. app.use(morgan('short'));
  7. app.get('/check', function (req, res) {
  8. console.log('success');
  9. res.send('success');
  10. });
  11. app.use(history());
  12. app.use(express.static('dist', {
  13. maxAge: "30d", // '1y' oneDay = 86400000
  14. setHeaders: function (res, path) {
  15. if (mime.lookup(path) === 'text/html') {
  16. res.setHeader('Cache-Control', 'public, max-age=0')
  17. }
  18. }
  19. }));
  20. app.listen(8080, () => {
  21. console.log('app listening on port 8080');
  22. return '0.0.0.0'
  23. });

在base001无法设置缓存相关的header,所以我转而在dockerfile中起一个Node应用,在express的static方法中,配置setHeaders

创建app.js

进程守护

pm2 start app.js -i max
pm2 start ecosystem.config.js
pm2 logs APP-NAME
docker exect -it CONTAINER_NAME /bin/sh

Monitoring CPU/Usage of each process
docker exec -it pm2 monit
# Listing managed processes
docker exec -it pm2 list
# Get more information about a process
docker exec -it pm2 show
# 0sec downtime reload all applications
docker exec -it pm2 reload all

多环境变量

  1. {
  2. "apps" : [
  3. {
  4. "script" : "server-local.js",
  5. "watch" : ["views"],
  6. "ignore_watch": ["node_modules"],
  7. "env": {
  8. "PORT": 3000,
  9. "NODE_ENV": "development",
  10. },
  11. "env_production" : {
  12. "PORT": 8080,
  13. "NODE_ENV": "production"
  14. }
  15. }
  16. ]
  17. }

容器内使用

一个注意点 CMD里不要使用 pm2 而是要pm2-runtime

RUN npm install pm2 -g CMD [ “pm2-runtime”, “start”, “ecosystem.config.js”]