Solving AWS EC2 Deployment Problems: Ports, Nginx, SSL and Environment Variables
Symptom-first troubleshooting for EC2: timeouts, 502s, failed certificates and missing environment variables.
- aws
- ec2
- troubleshooting
- nginx
- ssl
On this page ยท 21 sections
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)
- 1DNS
does the domain resolve to your IP?
- 2Security group
is the port open to the internet?
- 3OS firewall and Nginx
is the service listening?
- 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:
- Security group inbound rule for TCP 22 from your current IP. Home and mobile IPs change, so an old
/32rule is a frequent culprit. - Public address: the instance needs a public IPv4 address or Elastic IP, and you must connect to that address.
- Networking: the subnet's route table needs a route to an internet gateway, and network ACLs must allow the traffic in and out.
- Instance state: in the console, confirm both status checks pass.
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)"
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 AMIWrong 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:
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:
curl -I http://YOUR_IP # does port 80 respond?dig +short app.example.com # does DNS point to the right IP?| Observation | Meaning | Fix |
|---|---|---|
| Works on server, times out from outside | Security group or firewall | Open 80/443 in the security group; check sudo ufw status |
| Works by IP, fails by domain | DNS or server_name mismatch | Fix the A record; match server_name in Nginx |
| Works on HTTP, fails on HTTPS | No certificate or 443 closed | Install a certificate; open 443 |
| Domain points at an old IP | IP changed after a stop/start | Use an Elastic IP |
Problem 3: Nginx errors
First, always validate and read the log:
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_passmust match the port your app prints at startup. Checkss -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.
ls -l /etc/nginx/sites-enabled/sudo nginx -t && sudo systemctl reload nginxProblem 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.
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 error | Cause | Fix |
|---|---|---|
Timeout during connect | Port 80 blocked | Open 80 in the security group and firewall |
NXDOMAIN or wrong IP | DNS not set or not propagated | Create/fix the A record and wait |
Too many certificates | Rate limit hit | Wait, or test with the staging environment first |
| Challenge returns 404 | server_name does not match the domain | Fix the Nginx server block |
After issuing, confirm that auto-renewal works:
sudo certbot renew --dry-runsystemctl list-timers | grep certbotIf 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:
pm2 env 0 | grep -E "DATABASE_URL|NODE_ENV"sudo systemctl show my-app --property=EnvironmentCommon causes and fixes:
| Cause | Fix |
|---|---|
.env is in the wrong directory | Keep it next to the app, and load it explicitly |
Edited .env but did not restart | pm2 reload ecosystem.config.cjs --update-env |
| Variable exported in your SSH shell only | Define it in the ecosystem file, a .env loaded at startup or the service unit |
| systemd service has no env file | Add EnvironmentFile=/home/ubuntu/apps/my-app/.env to the unit |
| Frontend variable missing in the browser | Public 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:
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
pm2 logs my-app --lines 100pm2 describe my-app # restarts count, uptime, exit codes| Symptom in logs | Cause |
|---|---|
EADDRINUSE | Another process holds the port: sudo lsof -i :3000 |
Cannot find module | Dependencies not installed or wrong build output path |
ECONNREFUSED to the database | Wrong host, security group for the database, or database down |
| Process killed with no error | Out 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.
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.
df -hsudo du -xh /var /home --max-depth=2 | sort -rh | headsudo journalctl --vacuum-time=7dRotate 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):
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:
#!/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.logSecurity 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 -tbefore 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.