Table of Contents
Automating deployment processes is essential for modern software development. GitLab CI/CD provides a robust platform to streamline the deployment of NestJS applications, ensuring faster releases and consistent environments. This guide walks you through setting up GitLab CI/CD for your NestJS app.
Prerequisites
- GitLab repository with your NestJS project
- Docker installed locally for testing
- Access to a server or cloud platform for deployment
- Basic knowledge of Docker and Dockerfile creation
- Node.js and npm installed in your project
Setting Up Your NestJS Application
Ensure your NestJS app is ready for deployment. Your project should include a Dockerfile that packages the application into a container. Example Dockerfile:
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["node", "dist/main"]
Creating the GitLab CI/CD Configuration
Create a .gitlab-ci.yml file in the root of your project. This file defines the pipeline stages and jobs for building and deploying your app.
stages:
- build
- deploy
variables:
IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
build:
stage: build
image: docker:latest
services:
- docker:dind
script:
- docker build -t $IMAGE_TAG .
- docker push $IMAGE_TAG
only:
- main
deploy:
stage: deploy
image: docker:latest
script:
- echo "Deploying to server..."
- ssh user@your-server "docker pull $IMAGE_TAG && docker stop nestjs_app || true && docker rm nestjs_app || true && docker run -d --name nestjs_app -p 80:3000 $IMAGE_TAG"
only:
- main
Configuring the Deployment Server
Ensure your server has Docker installed and is accessible via SSH. Set up SSH keys for passwordless login to automate deployment. Your server should be configured to run Docker containers and expose ports as needed.
Sample Deployment Command
The deployment job in .gitlab-ci.yml uses a command like:
ssh user@your-server "docker pull ..."
Final Tips
- Secure your SSH keys and server access.
- Test your Docker build locally before automating.
- Use environment variables for sensitive data.
- Monitor your pipeline for errors and optimize as needed.
By integrating GitLab CI/CD with your NestJS application, you can achieve continuous deployment, reducing manual work and increasing reliability. Automate your workflow today and deploy with confidence!