一、工程的基本目录结构
- 1、基本目录结构
.
├── README.md
├── docker-compose.yml
├── nginx
│ └── default.conf
├── nodejs
│ └── index.js
├── nodejs2
│ └── index.js
└── static
└── index.html
4 directories, 6 files
- 2、文件介绍说明
-
docker-compose.yml
文件主要写配置的 -
nginx
主要是nginx
的配置
nodejs
和nodejs2
都是后端项目
static
文件是静态文件
二、各个文件的具体介绍
- 1、关于
docker-compose.yml
文件的代码
version: '3.1'
services:
nginx:
image: nginx:alpine
ports:
# 本地对外端口8000,镜像的80
- '8000:80'
volumes:
# 将本地的文件目录映射到镜像中
- ./static:/srv/www/static
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
depends_on:
- nodejs
- nodejs2
nodejs:
image: node:alpine
environment:
NODE_ENV: production
working_dir: /home/app
restart: always
volumes:
- ./nodejs:/home/app
# 启动命令
command: ['node', 'index']
nodejs2:
image: node:alpine
environment:
NODE_ENV: production
working_dir: /home/app2
restart: always
volumes:
- ./nodejs2:/home/app2
command: ['node',
- 2、关于
nodejs
的文件
const http = require('http');
http
.createServer(function (req,) {
res.write('nodejs');
res.end();
})
.listen(8080);
- 3、关于
nginx
文件内容
server {
listen 80;
# root /srv/www;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
location / {
root /srv/www/static;
index index.html index.htm;
}
location /api {
try_files $uri @nodejs;
}
# location @nodejs {
# proxy_pass http://nodejs:8080;
# }
location @nodejs {
proxy_pass http://nodejs2:9000;
}
}
- 4、运行命令启动项目
docker-compose up
docker-compose up -d
三、关于使用nginx
来做负载均衡
- 1、修改
nginx/default.conf
的配置
# 定义两个服务
upstream nginx_canary {
server nodejs:8080 weight=50;
server nodejs2:9000 weight=50;
# 如果不想使用哪个服务就weight=down
}
server {
listen 80;
# root /srv/www;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
location / {
root /srv/www/static;
index index.html index.htm;
}
location /api {
try_files $uri @nodejs;
}
# location @nodejs {
# proxy_pass http://nodejs:8080;
# }
# location @nodejs {
# proxy_pass http://nodejs2:9000;
# }
# 负载均衡的使用方式
location @nodejs {
proxy_pass http://nginx_canary;
}
}
- 2、启动
docker-compose