Deploying NestJS with Docker (Because Containers Are Like Bento Boxes) β
So youβve survived Vercel, AWS, and DigitalOcean. Now you want Docker.
Why? Because containers are like those magical lunch boxes π₯‘:
- Everything you need goes in
- It works the same everywhere
- You can ship it, scale it, and brag about it
π§ Why Docker? β
- Consistency: Works locally, works in the cloud.
- Isolation: No random dependencies stealing your lunch.
- Scalability: Spin up multiple copies like minions.
- Cool points: You can say βI run microservices in containersβ and people nod.
ποΈ Folder Structure β
Hereβs what your repo might look like:
nest-docker/
βββ src/
β βββ main.ts
βββ dist/
β βββ main.js
βββ package.json
βββ Dockerfile
βββ .dockerignore
βββ tsconfig.json
π³ Step 1: Create .dockerignore
β
node_modules
dist
npm-debug.log
Keeps the image light. Nobody likes heavy containers.
π³ Step 2: Create Dockerfile
β
dockerfile
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY tsconfig*.json ./
COPY src ./src
RUN npm run build
# Stage 2: Production
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=builder /app/dist ./dist
EXPOSE 3000
CMD ["node", "dist/main.js"]
Two-stage build = small, fast, production-ready image π
π³ Step 3: Build Docker Image β
bash
docker build -t nest-docker-app .
π³ Step 4: Run Locally (Optional, but fun) β
bash
docker run -p 3000:3000 nest-docker-app
Now open your browser: http://localhost:3000
Your app is alive inside a magical container! π³β¨
π³ Step 5: Deploy to Any Cloud β
5a: DigitalOcean β
- Push your image to Docker Hub or DigitalOcean Container Registry
- In App Platform, select Dockerfile deployment
- DO builds and runs your container magically
5b: AWS β
- Push image to ECR
- Use Elastic Beanstalk Docker platform or ECS / Fargate
- AWS scales your container like a pro
5c: Any cloud (Heroku, Railway, Render) β
- Most modern PaaS accept Dockerfile
- Push β Deploy β Sip chai β Celebrate π
π― TL;DR β
Step | Command / Notes |
---|---|
Build image | docker build -t nest-docker-app . |
Run locally | docker run -p 3000:3000 nest-docker-app |
Deploy to cloud | Push to Docker Hub / Cloud registry, run / scale |
π Summary β
Docker is like a magic lunchbox: pack it once, eat it anywhere.
- Works on your laptop β
- Works on DigitalOcean β
- Works on AWS β
- Impresses your dev friends β
Bonus: You can tell people, βI containerized my NestJS app and it survived the apocalypse.β π