In this guide, we'll walk through the steps to containerize a .NET API using Docker and set up a CI/CD pipeline with GitLab. This setup enables automatic building, testing, and deployment of your application, ensuring a smoother development lifecycle.
โ
Prerequisites
Before getting started, make sure you have the following:
- A .NET API project (.NET 8 or compatible)
- A GitLab account with a repository
- Docker installed on your local machine
๐ณ Dockerizing the .NET API
- Create a Dockerfile in the root of your project directory. This file defines how to build your Docker image.
# Base image for running the app FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base WORKDIR /app EXPOSE 80 EXPOSE 443 # Build image FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /src COPY ["blog.backend.api/blog.backend.api.csproj", "blog.backend.api/"] RUN dotnet restore "blog.backend.api/blog.backend.api.csproj" COPY . . WORKDIR "/src/blog.backend.api" RUN dotnet build "blog.backend.api.csproj" -c Release -o /app/build # Publish image FROM build AS publish RUN dotnet publish "blog.backend.api.csproj" -c Release -o /app/publish /p:UseAppHost=false # Final image FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "blog.backend.api.dll"]
โ๏ธ Setting Up the GitLab CI/CD Pipeline
- Create a .gitlab-ci.yml file at the root of your repository:
image: docker:latest services: - docker:dind stages: - build - test - deploy variables: DOCKER_IMAGE: registry.gitlab.com/yash-project/blogApplicationAPI DOCKER_TAG: latest build: stage: build script: - docker build -f Dockerfile -t $DOCKER_IMAGE:$DOCKER_TAG . - echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin $CI_REGISTRY - docker push $DOCKER_IMAGE:$DOCKER_TAG test: stage: test image: mcr.microsoft.com/dotnet/sdk:8.0 script: - dotnet test deploy: stage: deploy script: - echo "Deploying using Docker Compose..." - docker-compose up -d only: - main
This pipeline includes three stages:
- Build: Builds and pushes the Docker image to GitLab's container registry.
- Test: Runs your unit/integration tests.
- Deploy: Spins up the container using Docker Compose.
๐ฆ Docker Compose Deployment
Create a docker-compose.yml file:
version: "3.9" services: blog-backend-api: image: registry.gitlab.com/yash-project/blogApplicationAPI:latest ports: - "80:80"
- This simple setup pulls the latest image and runs your API on port 80.
๐ฏ Conclusion
By combining Docker with GitLab CI/CD, you now have a robust and automated workflow for building, testing, and deploying your .NET API. This approach streamlines development and ensures consistency across environments.
Top comments (0)