Configure Nginx for a Ruby App
I deploy using mina and docker and in the very front of the server, I have Cloudflare and nginx.
The reason I have nginx is, first, it is better at serving static content and, second, because if I ever need to add more server(s) it is easier to configure nginx instead of installing and configuring only in time of need.
nginx is so easy to install that I prefer installing using apt (I still don’t know a reason to have nginx inside docker or docker-compose if you know please let me know😐):
# apt install nginx
I also follow Debian’s (or Ubuntu’s) way, create a file /etc/nginx/sites-available/mywebsite.com:
upstream backend {
server 127.0.0.1:5001;
}
server {
listen 80;
root /mywebsite/current/public;
server_name mywebsite.com www.mywebsite.com;
if (-f $document_root/503.html) {
return 503;
}
error_page 503 @maintenance;
location @maintenance {
rewrite ^(.*)$ /503.html break;
}
location ~ / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
try_files $uri @app;
}
location @app {
charset utf8;
source_charset utf8;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
proxy_pass http://backend;
}
}
And create a link:
ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/myapp
The configuration is pretty clear to understand:
- puma is running in the same machine
127.0.0.1on port5001 - The root path of the server is on
/mywebsite/currentand itspublicdirectory/mywebsite/current/public, don’t forget you have to point to thepublicdirectory even if you don’t install with mina - If in your
publicdirectory you have a file503.htmlnginx will return a maintenance page instead proxy_passhas to point to theupstreamand- The
upstream backendis the list of servers you have - The other
proxys thing are to pass the real ip address of the request on
I don’t change any other thing within nginx, remember that I use Cloudflare, it is in charge of DDoS protection and SSL.
You may also want to configure your server to only accept connection from Cloudflare’s server (the ip addresses are here IP Ranges).