From Localhost to Production
Skip one-click platforms. Learn how to deploy your app on AWS using Linux, Docker, and Caddy while debugging the mistakes every developer eventually encounters.
From Localhost to the Cloud: Deploying on AWS EC2
Every developer eventually hits the same wall: a full-stack application works perfectly on localhost. The frontend is snappy, the backend is responding, and the database is connected. But localhost is a lonely place. The goal is to get the project live on the actual internet, accessible via a secure https:// link, ready to be shared with the world or added to a resume.
This article walks through deploying a full-stack application, the "hard way." No Vercel. No Heroku. No one-click deploy buttons. Just raw Linux, AWS, Docker, and the terminal.
What follows is an exhaustive, step-by-step explaining not just how to type the commands, but why they are necessary. It addresses you so you can follow along and avoid the common traps that catch beginners.
#Part 1: The Jargon
Before touching the terminal, it is crucial to demystify the tools. Here is what these tech buzzwords actually mean in plain English:
-
AWS EC2 (Elastic Compute Cloud): Imagine renting a laptop that lives in an Amazon data center. It has no monitor, no keyboard, and no mouse. It is controlled entirely through text commands (the terminal). Because it lives on the internet, it has a Public IP Address, meaning anyone in the world can visit it.
-
Ubuntu 26.04 LTS: The operating system that runs on that rented laptop. "LTS" means Long Term Support: it’s the stable, reliable version of Linux that won't break and receives security updates for 5 years.
-
SSH & PEM Keys: How to securely talk to that headless laptop. Instead of a password, AWS uses a cryptographic key pair. You keep the "Private Key" (a
.pemfile) on your local computer, and AWS puts the "Public Key" on the server. -
Docker: The cure for "but it works on my machine!" Docker wraps code, Node.js versions, and all dependencies into a sealed box called a Container. If the container runs locally, it is guaranteed to run on the AWS server.
-
Caddy: A web server (like Nginx) but with a superpower. Normally, getting an HTTPS padlock icon (SSL certificate) requires complex setup, verifying emails, and setting up cron jobs to renew the cert every 90 days. Caddy talks to Let's Encrypt and automatically gets and renews HTTPS certificates in seconds.
-
nip.io: To get an HTTPS certificate, Certificate Authorities usually require a real domain name (like
example.com).nip.iois a free DNS service that turns any IP address into a valid domain name. If a server's IP is16.171.24.60,nip.iolets you use16-171-24-60.nip.ioas a real domain, tricking Caddy into granting free HTTPS.
#Part 2: Renting the Server & The Firewall
Log into the AWS Console, search for EC2, and click Launch Instance.
1. Choosing the OS (AMI)
Select Ubuntu Server 26.04 LTS. Ensure it is marked "Free Tier Eligible." Always look for that tag when learning, otherwise AWS will quietly charge for usage.
2. The Key Pair (Do Not Lose This)
AWS will prompt you to create a Key Pair.
- Name:
server-key - Type:
ED25519(More secure and faster than the older RSA standard). - Format:
.pem(This is what Windows, Mac, and Linux terminals use natively).
Warning: AWS lets you download that .pem file exactly once. If lost, you are locked out of the server forever. Save it directly in a secure project folder.
3. Security Groups (The Cloud Firewall)
By default, AWS blocks all incoming traffic to the server. You have to explicitly open "ports" (doors) to let traffic in. Configure the Security Group to allow:
- Port 22 (SSH): So the terminal can connect to the server. (Set to "My IP" for security).
- Port 80 (HTTP): So the internet can see standard web traffic.
- Port 443 (HTTPS): So the internet can see secure, encrypted web traffic.
Skipping the "Elastic IP" step is fine for a beginner project. AWS automatically assigns a public IP when the server boots.
#Part 3: The Windows SSH Permission Nightmare
With the server running, open PowerShell on a Windows machine to connect:
ssh -i .\server-key.pem ubuntu@16.171.24.60Instead of connecting, Windows might throw a massive wall of text:
WARNING: UNPROTECTED PRIVATE KEY FILE!
Permissions for '.\server-key.pem' are too open.
It is required that your private key files are NOT accessible by others.The Learning: OpenSSH is incredibly strict about security. If other users on the computer (or the system itself) have "read" access to your private key, SSH refuses to use it, assuming the key might be compromised.
Fix: Strip the permissions using Windows icacls so that only the specific user account can read the file:
# Remove inheritance from parent folders
icacls .\server-key.pem /inheritance:r
# Remove access for the generic "Users" group
icacls .\server-key.pem /remove "BUILTIN\Users"
# Grant Read-only access strictly to the current Windows user
icacls .\server-key.pem /grant:r "$($env:USERNAME):(R)"After running those three lines, type the SSH command again.
The authenticity of host '16.171.24.60' can't be established.
Are you sure you want to continue connecting (yes/no)? yes
Welcome to Ubuntu 26.04 LTS...You are in. You are now staring at a blinking cursor on a computer physically located in an Amazon data center.
#Part 4: Prepping the Engine (Docker & Caddy)
To avoid manually installing Node.js, Nginx, and MongoDB on the server, use Docker.
Tip: Never use the default sudo apt install docker.io on Ubuntu. The default Ubuntu repositories are often months or years behind. Always use the official Docker repository.
Installing Docker
Run the official Docker installation sequence:
# 1. Update system and install prerequisites
sudo apt update && sudo apt upgrade -y
sudo apt install -y ca-certificates curl gnupg
# 2. Create a secure folder for repository keys
sudo install -m 0755 -d /etc/apt/keyrings
# 3. Download Docker's official GPG key
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg
# 4. Add the Docker repository to Ubuntu's package list
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
$(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
# 5. Install Docker Engine and Compose
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-pluginBy default, Docker requires sudo (admin privileges) for every single command. To fix this, add the ubuntu user to the docker group:
sudo usermod -aG docker $USER
newgrp docker # Refreshes the group permissions without logging outInstalling Caddy
Next, install Caddy using its official Cloudsmith repository so it receives automatic updates:
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo apt update
sudo apt install -y caddy
sudo systemctl enable --now caddyVerify everything is running with docker run hello-world and sudo systemctl status caddy. Once both are green, the server is ready for the code.
#Part 5: The 5 "Massive Fights" of Deployment
After cloning the GitHub repository, setting up docker-compose.prod.yml, and confidently running:
docker compose -f docker-compose.prod.yml up -d --buildThe server may fight back. Here are five distinct errors developers commonly encounter, and how to fix them.
1: The Server Suffocates (Disk & RAM)
Nine minutes into the build, the process might suddenly die.
error Error: ENOSPC: no space left on device, write
failed to execute bake: signal: killedCheck the server's vitals using df -h (disk space) and free -h (RAM):
Filesystem Size Used Avail Use% Mounted on
/dev/root 6.7G 6.5G 112M 99% /
total used free
Mem: 908Mi 428Mi 361Mi
Swap: 0B 0B 0BThe Reality Check: A free-tier EC2 instance has an 8 GB hard drive and 1 GB of RAM. Building a React frontend and a Node backend simultaneously requires massive amounts of temporary space and memory. The Linux kernel's "OOM Killer" (Out Of Memory) will assassinate the Docker build process to save the server from crashing.
Fix:
-
Expand the AWS EBS Volume: Go to the AWS Console -> Volumes -> Modify the volume from 8 GB to 20 GB. (This does not require stopping the server!).
-
Grow the Linux Partition: AWS makes the physical drive bigger, but Ubuntu doesn't know it yet. Tell Linux to expand the filesystem:
>_ bashsudo apt install -y cloud-guest-utils sudo growpart /dev/nvme0n1 1 # Expands the partition sudo resize2fs /dev/nvme0n1p1 # Expands the filesystem -
Add a 2GB Swap File: Use a piece of the hard drive as "fake RAM" so the OOM killer doesn't trigger during heavy builds:
>_ bashsudo fallocate -l 2G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab # Makes it permanent
2: The Environment Variable Trap
If a .env file is created to pass NODE_ENV=production into the Docker build to fix warnings, the React build might suddenly fail with:
Cannot find module 'vite' or 'vitest'
The Learning: When NODE_ENV is set to production before running yarn install, Yarn intentionally skips installing devDependencies to save space. But Vite and TypeScript are dev dependencies! They are needed to build the app, even if they aren't needed to run it.
Fix: In the client/Dockerfile, move ENV NODE_ENV=production to the line below RUN yarn install.
# WRONG: Skips Vite
ENV NODE_ENV=production
RUN yarn install
# RIGHT: Installs Vite, then sets production mode for the build step
RUN yarn install
ENV NODE_ENV=production3: The Ghost in the Dockerfile
The build might succeed, but the frontend container could keep restarting in an infinite loop. docker logs might show absolutely nothing and Exit code 0.
Running docker inspect on the image might reveal a truncated Dockerfile. If it only has the Node.js build stage and is missing the second stage that copies the built files into an Nginx Alpine image, Docker tries to run a Node server with no instructions, so it just exits cleanly (Code 0).
Fix: Rewrite the multi-stage Dockerfile properly:
# Stage 1: Build the React App
FROM node:lts AS build
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install
COPY . .
ENV NODE_ENV=production
RUN yarn build
# Stage 2: Serve it with Nginx
FROM nginx:1.21.0-alpine
COPY --from=build /app/build /usr/share/nginx/html
COPY nginx/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]4: The Directory Illusion (dist vs build)
The Dockerfile might try to copy the built React files:
COPY --from=build /app/dist /usr/share/nginx/html
And Docker throws an error: /app/dist: not found.
The Learn: Vite defaults to outputting to a dist folder. But if vite.config.ts explicitly has outDir: "build" to mimic older Create-React-App behavior, Docker will look for the wrong directory. Change the Dockerfile to look for /app/build, and the files will copy successfully.
5: The Port Mismatch (The Actual Final Boss)
Everything is built. Containers are "Up". But when curling the server locally:
curl http://127.0.0.1:3000
# curl: (56) Recv failure: Connection reset by peerSSH directly into the running container (docker exec -it client sh) and look at the Nginx config.
Nginx might be configured to listen 3000;.
But docker-compose.yml maps the host port to the container's port 80 (127.0.0.1:3000:80).
The Learn: Docker port mapping has two sides: HOST:CONTAINER. If the software inside the container isn't listening on the CONTAINER port, the connection drops into a black hole.
The Fix: Change nginx.conf to listen 80;, rebuild, and finally... HTML returns.
#Part 6: The Automatic HTTPS
With the app running locally on the server, it is time to expose it to the world securely.
Assuming the server's public IP is 16.171.24.60. Using nip.io, the domain becomes 16-171-24-60.nip.io.
Open the Caddyfile (sudo nano /etc/caddy/Caddyfile) and write exactly six lines:
16-171-24-60.nip.io {
reverse_proxy localhost:3000
}
api.16-171-24-60.nip.io {
reverse_proxy localhost:8081
}Reload Caddy: sudo systemctl reload caddy.
Open a browser and type https://16-171-24-60.nip.io.
The page loads. The padlock icon appears in the URL bar.
There is no need to generate a CSR, verify an email, or set up a cron job to renew the cert in 90 days. Caddy sees the nip.io domain, talks to Let's Encrypt, proves it controls the IP, and installs a valid SSL certificate in about three seconds.
#Part 7: Locking the Doors
Because Caddy handles all external traffic on ports 80 and 443, there is no reason for the outside world to directly access the Node (8081) or React (3000) containers. If a hacker finds a vulnerability in Node, they shouldn't be able to bypass Caddy's security.
Update docker-compose.prod.yml to bind the ports only to localhost:
ports:
- "127.0.0.1:3000:80" # Only Caddy can reach this
- "127.0.0.1:8081:8081" # Only Caddy can reach thisNow, the only way to reach the app is through Caddy, ensuring all traffic is encrypted, rate-limited, and secure.
#The Takeaways
Deploying manually can be painful, but it pulls back the curtain on how the web actually works. Here are the key takeaways to remember when undertaking this process:
-
Free Tier instances are for running, not building. 1GB of RAM is enough to host a container, but not enough to compile React and TypeScript. Always add a swap file and expand the EBS volume to at least 20GB.
-
Read your own Dockerfiles. Multi-stage builds are powerful, but if you accidentally delete the final Nginx stage, Docker will silently serve a broken Node image. Use
docker inspectwhen things act weird. -
Understand Port Mapping.
HOST:CONTAINERis a concept that trips up every beginner. Always verify what port your internal process (like Nginx) is actually listening on. -
Caddy + nip.io is a cheat code. You do not need to buy a domain just to test HTTPS in a production-like environment.
It might take hours, OOM kills, full hard drives, and head-scratching over port mismatches. But seeing that green padlock on a server configured from scratch makes it totally worth it. Now, go launch your own EC2 instance. You've got this.