Nginx Node
2024年07月17日
一、认识
二、目录
├── nginx/
│ └── conf
│ ├── nginx.conf
│ └── logs
│ └── www
│ ├── index.html
├── node/
│ ├── index.js
│ ├── Dockerfile
└── docker-compose.yml
三、node
3.1 index.js
const http = require("http");
const PORT = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end(`Hello from Node.js`);
});
server.listen(PORT, () => {
console.log(`Server running at port ${PORT}`);
});
3.2 Dockerfile
FROM node:latest
WORKDIR /service
COPY . /service
EXPOSE 3000
CMD ["node", "index.js"]
四、nginx
4.1 conf-nginx.conf
events {}
http {
server {
listen 80 default_server;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /api {
proxy_pass http://node:3000;
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;
}
}
}
细节如下
proxy_pass http://node:3000;
: 其中的 node
代表着 docker-compose.yml
中的 node
服务,Docker
内部会通过 DNS
找到对应的 node
容器服务
4.2 www-index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Nginx Node 服务</title>
</head>
<body>
<h1>欢迎来到 Nginx Node 服务</h1>
</body>
</html>
五、docker-compose.yml
services:
node:
build:
context: ./node
dockerfile: Dockerfile
image: node:latest
networks:
- backend
- frontend
nginx:
image: nginx:latest
ports:
- 9090:80
depends_on:
- node
volumes:
- ./nginx/www:/usr/share/nginx/html
- ./nginx/conf/nginx.conf:/etc/nginx/nginx.conf
- ./nginx/logs:/var/log/nginx
networks:
- frontend
networks:
backend:
frontend:
细节如下
-
启动服务名称为
node
的node
服务 -
启动服务名称为
nginx
的nginx
服务 -
通过
depends_on
指定node
服务在nginx
服务之前启动
六、测试 Nginx 服务
1. docker-compose build --no-cache
构建镜像
2. docker-compose up -d
启动 node
服务和 nginx
服务
3. 浏览器访问 localhost:9090
即可
七、测试 Node 服务
1. docker-compose build --no-cache
构建镜像
2. docker-compose up -d
启动 node
服务和 nginx
服务
3. 浏览器访问 localhost:3000
即可