Reverse Proxy with Nginx
At the moment, your endpoint url looks like this:
http://localhost:5000/books
Let's strip the port (:5000
).
You can simply make the api server run on port 80
by changing the gunicorn
command and running it as root.
Port 80 and 443 are default ports for HTTP and HTTPS respectively. They don't show up in the URL.
But, Gunicorn should not be run as root because it would cause your application code to run as root, which is not secure. However, this means it will not be possible to bind to port 80 or 443. Instead, a reverse proxy such as nginx or Apache httpd should be used in front of Gunicorn.
Additionally, what if you have multiple servers (such as an api server, web server, chat server and etc) running on a machine, and you want to expose all of them through port 80?
That's why you need reverse proxy.
Nginx config
Install nginx: https://nginx.org/en/docs/install.html
Suppose you have an api server running on port 5000, and a web server running on port 3000. Your can tune your Nginx config like this:
server {
listen 80;
server_name yourdomain.com;
location /web {
proxy_pass http://localhost: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;
}
location / {
proxy_pass http://localhost:5000;
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;
}
}
Reload Nginx to apply the changes.
Then, you can make a request like this:
curl http://localhost/books