☁️

Deploying NestJS with Docker on EC2

Sep 22, 2024

Deploying a NestJS Application to AWS EC2 using Docker

Overview

  • Deploy a NestJS application to AWS EC2 using Docker.
  • Example: Deploy a Blog API project built with NestJS.
  • Steps: Create Dockerfile, Docker Compose YAML, create EC2 instance, deploy to server.

Preparation

  1. Create Dockerfile & Docker Compose YAML
    • Essential for organizing and preparing for production.
    • Use multi-stage builds to optimize Docker image size.
    • Compile TypeScript to JavaScript and remove unnecessary files and dependencies.

Dockerfile Setup

  • First Stage: Build

    • Use base image node:alpine.
    • Create work directory: usr/src/app.
    • Copy package.json and run npm install.
    • Copy source code and compile TypeScript to JavaScript.
  • Second Stage: Production

    • Copy necessary files from build stage.
    • Run npm install with production flag to exclude dev-dependencies.
    • Remove package.json after installation to optimize image.
    • Expose port 3000 for application.
    • Set NODE_ENV to production for optimized performance.

Docker Compose YAML

  • Setup Version & Services

    • Version 3 with backend and database services.
    • Backend build path set to root directory.
    • Define environment variables and port mappings.
  • Database Configuration

    • Image: mongo.
    • Define ports and volumes for data persistence.
    • Set up network nestjs_network with bridge driver.

GitHub Setup

  • Push Project to GitHub
    • Exclude sensitive files like Docker Compose YAML and .env from version control.
    • Initialize Git repository, add files, commit, and push to GitHub.

AWS EC2 Instance Creation

  • Create and Setup EC2

    • Use Ubuntu image and configure instance type (t2.micro).
    • Set security rules to allow port 3000 access.
  • Connect and Install Docker

    • Connect via SSH and install Docker using official instructions.

Deploy Application

  • Set Up Application on EC2

    • Clone repository to EC2 instance.
    • Recreate Docker Compose YAML file on EC2.
    • Run sudo docker-compose up -d to start containers.
  • Verify Deployment

    • Check container status and network configurations.
    • Use Postman to test API endpoints and verify connectivity.

Conclusion

  • Successful deployment of NestJS application to AWS EC2 using Docker.
  • Ensured optimized Docker image and secure environment variable management.
  • Potential issues: Always ensure proper environment variable setup and Docker configurations.