Hamza Janzaib avatar
AboutResumeProjectsWorkBlogContact
Home/Blog/AWS, Deployment & DevOps/Solving AWS EC2 Deployment Problems: Ports, Nginx, SSL and Environment Variables

Solving AWS EC2 Deployment Problems: Ports, Nginx, SSL and Environment Variables

Symptom-first troubleshooting for EC2: timeouts, 502s, failed certificates and missing environment variables.

By Hamza JanzaibNovember 28, 202613 min readIntermediate
Paste it into ChatGPT, Claude or any AI assistant.
  • aws
  • ec2
  • troubleshooting
  • nginx
  • ssl
On this page ยท 21 sections
  • Debug from the outside in
  • Problem 1: SSH will not connect
  • "Connection timed out"
  • "Connection refused"
  • "Permission denied (publickey)"
  • Problem 2: The site does not load in the browser
  • Problem 3: Nginx errors
  • 502 Bad Gateway
  • 504 Gateway Timeout
  • 413 Request Entity Too Large
  • Configuration changes have no effect
  • Problem 4: SSL and Certbot failures
  • Problem 5: Environment variables are missing
  • Problem 6: The app crashes or restarts repeatedly
  • Problem 7: The server runs out of resources
  • Problem 8: The IP address keeps changing
  • Problem 9: The instance cannot reach AWS services
  • A one-page diagnostic script
  • Security considerations while debugging
  • Best practices
  • Conclusion

An EC2 deployment has many moving parts between a browser and your code: DNS, security groups, the operating system firewall, Nginx, TLS, your process manager and your application. When something fails, the hardest part is not the fix. It is knowing which layer is broken. This guide is a symptom-first troubleshooting manual: for each common failure it explains what the symptom means, how to confirm the cause with a command, and how to fix it.

Debug from the outside in

Walk the request path in order and stop at the first failing layer:

Request path (check in this order)

  1. 1DNS

    does the domain resolve to your IP?

  2. 2Security group

    is the port open to the internet?

  3. 3OS firewall and Nginx

    is the service listening?

  4. 4Your app

    is it running and healthy?

A useful rule: test from the server first, then from outside. If curl localhost:3000 works on the instance but the browser fails, the problem is between the two. If it fails on the instance, the problem is your app.

Problem 1: SSH will not connect

"Connection timed out"

Traffic is being dropped. Check, in order:

  1. Security group inbound rule for TCP 22 from your current IP. Home and mobile IPs change, so an old /32 rule is a frequent culprit.
  2. Public address: the instance needs a public IPv4 address or Elastic IP, and you must connect to that address.
  3. Networking: the subnet's route table needs a route to an internet gateway, and network ACLs must allow the traffic in and out.
  4. Instance state: in the console, confirm both status checks pass.
bash
nc -vz YOUR_IP 22      # does the port answer at all?ssh -v -i key.pem ubuntu@YOUR_IP   # verbose output shows how far it gets

"Connection refused"

The machine is reachable but nothing listens on 22. This usually means sshd is stopped or the instance is still booting.

"Permission denied (publickey)"

bash
chmod 400 key.pem                    # key must not be readable by othersssh -i key.pem ubuntu@YOUR_IP        # Ubuntu AMIssh -i key.pem ec2-user@YOUR_IP      # Amazon Linux AMI

Wrong username and wrong key pair are the two common causes. Confirm in the console which key pair the instance was launched with. If you truly lost access, use EC2 Instance Connect or Session Manager to get a shell.

Problem 2: The site does not load in the browser

Work from the server outward.

On the server:

bash
curl -i http://127.0.0.1:3000/health     # is the app answering?pm2 status                                # is the process running?sudo ss -tlnp | grep -E ':80|:443|:3000'  # who is listening on which port?

Reading ss output matters. An app bound to 127.0.0.1:3000 is only reachable from the machine itself, which is correct behind Nginx but wrong if you expect to reach it directly. An app bound to 0.0.0.0:3000 is reachable from outside if the security group allows it.

From your own computer:

bash
curl -I http://YOUR_IP          # does port 80 respond?dig +short app.example.com      # does DNS point to the right IP?
ObservationMeaningFix
Works on server, times out from outsideSecurity group or firewallOpen 80/443 in the security group; check sudo ufw status
Works by IP, fails by domainDNS or server_name mismatchFix the A record; match server_name in Nginx
Works on HTTP, fails on HTTPSNo certificate or 443 closedInstall a certificate; open 443
Domain points at an old IPIP changed after a stop/startUse an Elastic IP

Problem 3: Nginx errors

First, always validate and read the log:

bash
sudo nginx -tsudo tail -n 50 /var/log/nginx/error.logsudo journalctl -u nginx --since "15 min ago"

502 Bad Gateway

Nginx is running but the upstream is not answering correctly.

  • App not running or crashed: pm2 status, pm2 logs.
  • Wrong port: the port in proxy_pass must match the port your app prints at startup. Check ss -tlnp.
  • App listens on a Unix socket or another interface than Nginx targets.
  • SELinux (on some distributions) blocks outbound connections from Nginx: sudo setsebool -P httpd_can_network_connect 1.

504 Gateway Timeout

The upstream accepted the connection but did not respond in time. Find out why the request is slow (database, external API) before raising proxy_read_timeout.

413 Request Entity Too Large

The upload exceeds client_max_body_size (default 1 MB). Raise it deliberately, for example client_max_body_size 10m;.

Configuration changes have no effect

You edited a file that is not enabled, or forgot to reload.

bash
ls -l /etc/nginx/sites-enabled/sudo nginx -t && sudo systemctl reload nginx

Problem 4: SSL and Certbot failures

Let's Encrypt validates domain ownership by requesting a file over HTTP on port 80. So a failing certificate request almost always means the validation request cannot reach your server.

bash
dig +short app.example.com            # must be this server's public IPcurl -I http://app.example.com        # must reach Nginxsudo certbot --nginx -d app.example.com
Certbot errorCauseFix
Timeout during connectPort 80 blockedOpen 80 in the security group and firewall
NXDOMAIN or wrong IPDNS not set or not propagatedCreate/fix the A record and wait
Too many certificatesRate limit hitWait, or test with the staging environment first
Challenge returns 404server_name does not match the domainFix the Nginx server block

After issuing, confirm that auto-renewal works:

bash
sudo certbot renew --dry-runsystemctl list-timers | grep certbot

If a certificate expired unexpectedly, the usual reason is that renewal ran while port 80 was closed or the DNS record had changed.

Problem 5: Environment variables are missing

Symptoms include undefined configuration values, failed database connections or an app that boots with defaults it should never use.

Confirm what the process actually sees:

bash
pm2 env 0 | grep -E "DATABASE_URL|NODE_ENV"sudo systemctl show my-app --property=Environment

Common causes and fixes:

CauseFix
.env is in the wrong directoryKeep it next to the app, and load it explicitly
Edited .env but did not restartpm2 reload ecosystem.config.cjs --update-env
Variable exported in your SSH shell onlyDefine it in the ecosystem file, a .env loaded at startup or the service unit
systemd service has no env fileAdd EnvironmentFile=/home/ubuntu/apps/my-app/.env to the unit
Frontend variable missing in the browserPublic build-time variables are baked in at build time; rebuild after changing them

Fail fast so missing values are obvious at startup rather than at the first request:

ts
const required = ["DATABASE_URL", "JWT_SECRET"];const missing = required.filter((k) => !process.env[k]);if (missing.length) throw new Error(`Missing environment variables: ${missing.join(", ")}`);

Problem 6: The app crashes or restarts repeatedly

bash
pm2 logs my-app --lines 100pm2 describe my-app          # restarts count, uptime, exit codes
Symptom in logsCause
EADDRINUSEAnother process holds the port: sudo lsof -i :3000
Cannot find moduleDependencies not installed or wrong build output path
ECONNREFUSED to the databaseWrong host, security group for the database, or database down
Process killed with no errorOut of memory (see next problem)

Problem 7: The server runs out of resources

Out of memory. A Node build or app on a small instance can be killed by the kernel's OOM killer.

bash
free -hdmesg | grep -i -E "killed process|out of memory"

Fixes: use a larger instance, build in CI instead of on the server, set max_memory_restart in PM2, or add swap as a stopgap.

Out of disk. Logs and old builds accumulate.

bash
df -hsudo du -xh /var /home --max-depth=2 | sort -rh | headsudo journalctl --vacuum-time=7d

Rotate application logs (pm2 install pm2-logrotate) and delete old releases.

Problem 8: The IP address keeps changing

A stopped and restarted instance gets a new public IP unless it has an Elastic IP. Allocate one, associate it with the instance and point DNS at it. Remember that unattached Elastic IPs may incur charges, so release ones you no longer use.

Problem 9: The instance cannot reach AWS services

If your app uses an IAM role from the instance profile, credentials come from the instance metadata service. Verify the role is attached and the metadata service is reachable (using IMDSv2):

bash
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \  -H "X-aws-ec2-metadata-token-ttl-seconds: 60")curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \  http://169.254.169.254/latest/meta-data/iam/security-credentials/

An empty result means no role is attached. Attach one in the console rather than storing access keys on the server.

A one-page diagnostic script

Keep a small script on the server that prints the facts you always need first:

bash
#!/usr/bin/env bashecho "== Listening ports =="; sudo ss -tlnp | grep -E ':22|:80|:443|:3000'echo "== PM2 ==";            pm2 statusecho "== Nginx test ==";     sudo nginx -techo "== Health ==";         curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3000/healthecho "== Disk ==";           df -h /echo "== Memory ==";         free -hecho "== Recent nginx errors =="; sudo tail -n 10 /var/log/nginx/error.log

Security considerations while debugging

  • Do not open SSH to 0.0.0.0/0 "just to test". Use your IP, and close it afterward, or use Session Manager.
  • Do not leave application ports (3000, 8080) public as a workaround; fix the proxy instead.
  • Do not paste secrets or full environment dumps into tickets or chats.
  • Revert temporary changes (permissive security groups, disabled firewall) once the issue is solved.

Best practices

  • Debug outside-in, one layer at a time, and prove each layer before moving on.
  • Use Elastic IPs, a process manager that restarts on reboot, and health endpoints.
  • Validate Nginx with nginx -t before every reload.
  • Fail fast on missing configuration.
  • Keep logs, metrics and alarms (CPU, memory, disk, status checks) so problems announce themselves.

Conclusion

EC2 deployment problems feel chaotic because many layers produce similar symptoms. A fixed order (DNS, security group, firewall and proxy, then the application) turns that chaos into a checklist, and a few commands per layer tell you where the request stops. Keep the diagnostic script handy, fix the root cause instead of loosening security, and your next outage should be a short one.

Frequently asked questions

+โˆ’Why does SSH say 'Connection timed out' on a new EC2 instance?

A timeout means packets are being dropped before reaching SSH. Check the security group allows inbound port 22 from your current IP, the instance is in a public subnet with a route to an internet gateway, it has a public IP or Elastic IP, and network ACLs or a local firewall are not blocking it.

+โˆ’What is the difference between 'Connection timed out' and 'Connection refused'?

Timed out usually means a firewall or routing problem is dropping traffic. Refused means the packet reached the machine but nothing is listening on that port, so the service is stopped or bound to a different address.

+โˆ’Why does 'Permission denied (publickey)' happen?

Wrong username for the AMI (ubuntu on Ubuntu, ec2-user on Amazon Linux), wrong or unreadable key file (permissions must be 400), or the instance was launched with a different key pair.

+โˆ’My app works with curl on the server but not from my browser. Why?

Usually the security group or firewall does not allow the port, the app listens on 127.0.0.1 instead of 0.0.0.0 (when you are not using a proxy), or DNS points to the wrong address.

+โˆ’Why does Certbot fail to issue a certificate?

The domain must resolve to the server's public IP and port 80 must be reachable from the internet, because Let's Encrypt validates over HTTP. Check DNS propagation, the security group, any firewall and that Nginx answers on port 80 for that domain.

+โˆ’Why are my environment variables undefined after deploying?

The process does not load the file you edited. Common causes: the .env file is in a different directory, PM2 was not restarted with --update-env, a systemd unit has no EnvironmentFile, or the variable is set in your shell only and not for the service.

+โˆ’How do I keep my public IP from changing?

Allocate an Elastic IP and associate it with the instance. Without one, the public IP changes whenever the instance is stopped and started.

Further reading

  • docs.aws.amazon.com/ec2/
  • nginx.org/en/docs/
  • certbot.eff.org/

Hamza Janzaib

Full-Stack Developer based in Karachi, Pakistan. Building web apps, APIs and cloud infrastructure. About me


Related articles

AWS, Deployment & DevOpsNovember 28, 202618 min readIntermediate

Deploying a Node.js Application on AWS EC2 From Scratch

The full path from an empty EC2 instance to a Node.js app behind Nginx and HTTPS, with troubleshooting.

AWS, Deployment & DevOpsNovember 28, 202612 min readIntermediate

Configuring Nginx as a Reverse Proxy for Node.js Applications

Proxy headers, WebSocket upgrades, compression and timeouts: an Nginx config you can reason about.

AWS, Deployment & DevOpsNovember 28, 202615 min readBeginner

Hosting a Static Website on AWS S3

Create a bucket, allow public reads, enable website hosting and deploy a build with one CLI command.

Built by Hamza Janzaib

PrivacyTerms