我想創建一個 nginx docker container 來作為 udp 負載平衡,轉發到另一個 有 udp server 的 ndoe docker container。
之後用 udp client 向 nginx container 發信息,但 udp server 一直没有收到信息,nginx、ndoe container 也没有錯誤信息。
不知道哪裡出了問題,想請大家幫忙看一下配置和步驟。
docker network create udp_proxy
2.創建 udp 負載平衡 image
docker build -t mailbox_proxy .
# nginx Dockerfile
FROM nginx:stable-alpine
COPY udp-load‑balanced.conf /etc/nginx/conf.d/
COPY nginx.conf /etc/nginx/
# udp-load‑balanced.conf
upstream dns_upstream {
server mailbox_1:80 fail_timeout=60s;
}
server {
listen 53 udp;
proxy_pass dns_upstream;
proxy_timeout 1s;
proxy_responses 1;
error_log /var/log/nginx/udp-dns-error.log notice;
}
# nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
}
}
stream {
include /etc/nginx/conf.d/udp-load‑balanced.conf;
}
2.創建 udp server image
docker build -t mailbox .
# udp server Dockerfile
FROM node:lts-alpine3.16
RUN mkdir /mailbox
WORKDIR /mailbox
COPY index.js /mailbox
COPY package.json /mailbox
CMD ["npm", "run", "start"]
// index.js
// udp server
const dgram = require('dgram');
function main() {
const server = dgram.createSocket('udp4');
const prot = '80';
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind(prot);
}
main();
// package.json
{
"name": "mailbox",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
4.創建 udp 負載平衡 container
docker run -d -p 8080:80 -p 53:53 --name mailbox_proxy --network udp_proxy mailbox_proxy
docker run -d --name mailbox_1 --network udp_proxy mailbox
6.udp client 向 nginx container 發信息
// udp client
const dgram = require('node:dgram');
const { Buffer } = require('node:buffer');
const message = Buffer.from('Some bytes');
const client = dgram.createSocket('udp4');
client.send(message, 53, calhost', (err) => {
client.close();
});
問題出在步驟 4 我開的 prot 是 tcp,因此udp 負載平衡一直没有收到 udp 信息,
把步驟 4 的指令改為下面就可以了。
docker run -d -p 8080:80 -p 53:53/udp --name mailbox_proxy --network udp_proxy mailbox_proxy