Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

nginx server block + docker, how does back and front communicate

My application is divided into a backend and frontend docker container which are running in digital ocean server. I purchased a domain and inserted the routes provided from digital ocean into my namecheap DNS. I am using nginx server block to route my frontend to the server and would like it to communicate to my backend docker container. I am currently watching this tutorial from faraday.

My frontend container is running on localhost:3000 and my backend is running on localhost:5000; And i've set the ports to run when the location is server_name/ . How will my nginx server block know whether it's loading the frontend or backend to the domain since both are expected to run proxy_pass at location /?

I want to display the front onto server_name provided but still able to access my backend

server{
    server_name newlife.life;
    access_log /var/log/nginx/st-access.log
    error_log /var/log/nginx/st-error.log debug
    
    location / {
        proxy_pass http://localhost:3000;
    }
    location / {
        proxy_pass http://localhost:5000;
    }

}
question from:https://stackoverflow.com/questions/65857040/nginx-server-block-docker-how-does-back-and-front-communicate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your frontend can make the backend calls on a different subpath. These requests will arrive at nginx and then nginx can proxy them to backend by rewriting the URL using the http_rewrite module.

See https://nginx.org/en/docs/http/ngx_http_rewrite_module.html

Example:

location /backend {
    proxy_pass localhost:5000;
    rewrite  ^/backend/(.*)  /$1 break;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...