How to solve 502 bad gateway in Nginx server.

Sabita Nepal
2 min readJul 24, 2024

--

Introduction

The HyperText Transfer Protocol (HTTP) ‘502 Bad Gateway’ server error response code indicates that the server, while acting as a gateway or proxy, received an invalid response from the upstream server. This means that the issue lies within our server configuration or setup.

In this guide, we will walk through the steps to solve the ‘502 Bad Gateway’ error using Ruby on Rails with Capistrano, Nginx, and Puma.

Prerequisites

  • Basic knowledge of Ubuntu terminal and Capistrano file structure.
  • Ruby on Rails is properly set up on your PC.
  • Servers have been setup in your PC where deployment takes place.
  • Understanding of different HTTP status codes.

What happened during deployment to have 502 bad gateway issue?

The ‘502 Bad Gateway’ error was one of the major issues I faced during the deployment of a Ruby on Rails app using Capistrano, Nginx, on an AWS EC2 instance. Here are some steps I took and insights I gained.

  • The Nginx TCP connection with Puma was configured correctly, and the socket connection was properly bound.
  • However, the Puma unit file was missing on my server.

To resolve this, I needed to create a Puma unit file.

sudo vi puma.service
  • Now add the below unit file to run the puma socket file to be bound to nginx for connection.
# /etc/systemd/system/puma.service
[Unit]
Description=Rails Puma server
After=network.target
[Service]
Type=simple
User=ubuntu
EnvironmentFile=/home/path to/you/deployed/directory/environment/file/current/.env
WorkingDirectory=/home/path to/you/deployed/directory/current/app
ExecStart=/usr/bin/bash -lc '/home/ubuntu/.rbenv/shims/bundle exec puma -C /home/path to/you/deployed/directory/current/config/puma.rb'
ExecStop=/usr/bin/bash -lc '/home/ubuntu/.rbenv/shims/bundle exec pumactl -S /home/path to/you/deployed/directory/shared/tmp/pids/puma.state stop'
PIDFile=/home/path to/you/deployed/directory/tmp/pids/your/deployed/file-puma.pid
Restart=always
[Install]
WantedBy=multi-user.target
  • Save the changes within the puma. service and restart the daemon service to make sure it’s added.
sudo systemctl daemon-reload
  • Restart the Puma service as well as enable it in boot.
sudo systemctl enable puma sudo systemctl restart puma

Now deploy the API from your PC to to AWS server

bundle exec cap <your staging env> deploy --trace

Now your Ruby on Rails app is deployed in the server and 502 bad gateway is solved.

--

--