DEV Community

Cover image for From Localhost to AWS EC2: Deploying My First Full-Stack App
Devashish
Devashish

Posted on AI-assisted

From Localhost to AWS EC2: Deploying My First Full-Stack App

I've spent over five years working primarily on frontend development, building applications with React, Next.js, and TypeScript.

Recently, I decided to take one of my personal projects beyond local development and deploy the complete application on AWS EC2.

The project has a Next.js frontend, a Node.js and Express backend, and a MongoDB database. I used Docker and Docker Compose for containerization, Nginx as a reverse proxy, and Let's Encrypt for HTTPS.

This was my first time managing the complete deployment myself, from configuring the server to connecting the frontend, backend, database, domains, and authentication.

Here's how I approached it and some of the challenges I encountered along the way.

The Tech Stack

Here's what the deployment looks like:

Component Technology
Frontend Next.js (App Router), TypeScript
Backend Node.js, Express, TypeScript
Database MongoDB
Server AWS EC2 (Ubuntu)
Containerization Docker, Docker Compose
Reverse Proxy Nginx
SSL Let's Encrypt, Certbot

I used two subdomains:

  • blog.example.com for the frontend.
  • blog-api.example.com for the backend.

The goal was to keep the application services behind Nginx instead of exposing their ports directly to the internet.

1. Setting Up the EC2 Instance

I started with an Ubuntu EC2 instance and configured SSH access.

One of the first things I focused on was the security group. I wanted the application to be publicly accessible without exposing every service running on the machine.

I kept the public entry points limited:

  • Port 22 for SSH, restricted to my IP.
  • Port 80 for HTTP.
  • Port 443 for HTTPS.

The frontend, backend, and database didn't need publicly accessible ports.

I also assigned an Elastic IP so that the instance would retain a stable public IP address.

2. Containerizing the Application

Both the frontend and backend were already developed, so the next step was preparing them to run in production containers.

Backend

The backend uses Node.js, Express, and TypeScript.

I created a multi-stage Docker build. The first stage installs dependencies and compiles TypeScript, while the final stage contains only the production output and required dependencies.

This keeps development dependencies and build tools out of the final production image.

I also kept environment-specific configuration separate from the Dockerfile. I didn't want to modify the Dockerfile every time a new environment variable was introduced.

Docker Compose made it easier to manage the backend and MongoDB services together.

Frontend

For Next.js, I used the standalone output configuration:

// next.config.js
const nextConfig = {
  output: "standalone",
};

module.exports = nextConfig;
Enter fullscreen mode Exit fullscreen mode

This generates a standalone server bundle containing the dependencies needed to run the application.

The production image only needs the standalone output, static assets, and public directory.

One detail worth understanding is the difference between build-time and runtime environment variables.

Variables prefixed with NEXT_PUBLIC_ are embedded into the client bundle during next build. Changing them after the image has been built won't update the already-generated JavaScript bundle.

Server-only environment variables have different considerations and can be supplied at runtime, provided the application reads them at runtime rather than baking them into the build.

Understanding this distinction helped me structure the frontend configuration more carefully.

3. Dealing With EC2 Memory Limitations

One of the more frustrating issues came during the build and deployment process.

The EC2 instance started running out of memory, and some processes were being terminated.

I used:

free -h
Enter fullscreen mode Exit fullscreen mode

to inspect memory usage.

To investigate whether Linux had terminated processes through the Out Of Memory (OOM) killer, I checked:

sudo dmesg -T | grep -i -E 'oom|killed process'
Enter fullscreen mode Exit fullscreen mode

This helped identify that memory pressure was causing the problem.

I also learned more about swap space and how it provides additional virtual memory when physical RAM is under pressure.

I configured swap to give the instance more breathing room.

Swap isn't a replacement for RAM. It can help prevent processes from being killed immediately under memory pressure, but it's significantly slower than physical memory.

This was a useful reminder that a Docker build that works comfortably on a development machine may not run as smoothly on a small cloud instance.

4. Docker Networking and Nginx

Once both applications were containerized, I needed to make them accessible through the server.

I wanted Nginx to be the public entry point, so I didn't expose the application ports directly.

Instead, I bound them to the EC2 host's loopback interface:

services:
  frontend:
    ports:
      - "127.0.0.1:3000:3000"

  backend:
    ports:
      - "127.0.0.1:3001:3001"
Enter fullscreen mode Exit fullscreen mode

This allows services on the EC2 host to reach the containers through those ports without exposing them directly to the public internet.

Another important distinction is that localhost inside a container refers to that container itself, not the EC2 host or another container.

For communication between containers on the same Docker network, I can use the Docker Compose service name as the hostname.

For example, the frontend container can communicate with the backend using its service name and internal port.

This is particularly useful for server-side requests made by Next.js.

Configuring Nginx

I configured Nginx to route incoming requests to the appropriate application.

The frontend domain forwards requests to port 3000, while the API domain forwards requests to port 3001.

A simplified frontend configuration looks like this:

server {
    listen 80;
    server_name blog.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;

        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
Enter fullscreen mode Exit fullscreen mode

The backend has a separate server block:

server {
    listen 80;
    server_name blog-api.example.com;

    location / {
        proxy_pass http://127.0.0.1:3001;

        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
Enter fullscreen mode Exit fullscreen mode

I also had to understand how Nginx's sites-available and sites-enabled directories work.

The configuration files live in sites-available, while symbolic links in sites-enabled determine which configurations Nginx loads.

After making changes, I used:

sudo nginx -t
Enter fullscreen mode Exit fullscreen mode

to validate the configuration before reloading Nginx.

5. Configuring DNS and HTTPS

After configuring Nginx, I added DNS A records for both subdomains, pointing them to the EC2 Elastic IP.

Once DNS resolution was working, I moved on to HTTPS.

I installed Certbot using Snap and used its Nginx integration to obtain and install certificates from Let's Encrypt.

sudo certbot --nginx \
  -d blog.example.com \
  -d blog-api.example.com
Enter fullscreen mode Exit fullscreen mode

Certbot handled domain validation and updated the Nginx configuration to enable HTTPS.

I also checked automatic certificate renewal:

sudo certbot renew --dry-run
Enter fullscreen mode Exit fullscreen mode

This helped verify that certificate renewal was configured correctly.

6. Handling Authentication Cookies Across Subdomains

Authentication was one of the more interesting parts of the deployment because it involved both browser requests and server-side requests.

The frontend and backend were hosted on separate subdomains.

Although browser requests to the API were working, I ran into a problem when Next.js needed to make a server-side request to refresh an expired access token.

The key difference is that a browser automatically attaches eligible cookies to requests, whereas a server-side fetch() doesn't automatically inherit the browser's cookie storage.

I had to explicitly forward the refresh token in the request:

const response = await fetch(apiUrl, {
  method: "POST",
  headers: {
    Cookie: `${COOKIE_KEYS.REFRESH_TOKEN}=${refreshToken}`,
  },
  cache: "no-store",
});
Enter fullscreen mode Exit fullscreen mode

I also needed to read the cookies returned by the backend and forward the Set-Cookie headers to the browser.

Another important detail was the cookie domain.

If authentication needs to work across subdomains, the cookie configuration must account for the domain scope.

For example, a cookie configured for blog-api.example.com won't automatically be available to blog.example.com.

For this setup, the parent domain .example.com was the relevant scope.

I also paid closer attention to HttpOnly, Secure, SameSite, cookie paths, and CORS configuration.

These settings solve different problems, and getting them right requires understanding which request is made by the browser and which is made by the server.

7. Debugging Production Issues

One thing this deployment reinforced is that a running container doesn't necessarily mean a working application.

For example, when I encountered a 504 Gateway Timeout, I didn't immediately assume Nginx was the problem.

I tested the upstream services directly from the EC2 instance:

curl -I --max-time 10 http://127.0.0.1:3000
Enter fullscreen mode Exit fullscreen mode

And separately:

curl -I --max-time 10 http://127.0.0.1:3001
Enter fullscreen mode Exit fullscreen mode

This helped isolate whether the issue was with the application itself or the reverse proxy.

The same approach applied throughout the deployment: check each layer independently before changing multiple things at once.

Docker logs, Nginx logs, system memory information, DNS resolution, and direct HTTP requests all became part of the debugging process.

What I Took Away From This Deployment

Some of the most useful things I worked through were:

  • Building production-ready Docker images for Next.js and Node.js.
  • Understanding build-time versus runtime environment configuration.
  • Managing containers and services through Docker Compose.
  • Understanding Docker networking and port binding.
  • Configuring Nginx as a reverse proxy.
  • Managing DNS records and SSL certificates.
  • Diagnosing memory pressure and configuring swap.
  • Understanding cookie behaviour across subdomains.
  • Handling authentication refresh requests between the browser, Next.js server, and backend.
  • Debugging issues across application, container, and infrastructure layers.

What's Next?

The deployment is working, but there are still improvements I want to make.

My next step is setting up CI/CD so that changes can be built and deployed without manually connecting to the EC2 instance and running each command.

I also want to improve production monitoring and make the deployment process more reliable.

This experience helped me look beyond application code and understand more of the systems involved in running an application in production.

Building an application is one part of the job. Making sure it can run reliably, communicate with other services, handle authentication, and remain accessible introduces an entirely different set of considerations.

If you've self-hosted a Next.js and Node.js application on EC2, I'd be interested to know how you handle CI/CD, monitoring, and deployments.

Top comments (0)