Set Up CI/CD for Go Applications with GitLab

CI/CD for Go Applications with GitLab

GitLab CI/CD automates building, testing, and deploying Go applications directly from your GitLab repository. This ensures reliable updates and faster delivery. This guide explains how to set up a CI/CD pipeline for Go using GitLab CI and Docker.


Step 1: Prepare Your Go Application

Ensure your Go app builds correctly:

go build server.go

Run tests locally:

go test ./...


Step 2: Create Dockerfile

Create a file named Dockerfile:

FROM golang:1.20-alpine AS builder WORKDIR /app COPY . . RUN go build -o server . FROM alpine:latest WORKDIR /app COPY --from=builder /app/server . CMD ["./server"]

Step 3: Create .gitlab-ci.yml

Create a file named .gitlab-ci.yml in your repository root:

stages: - build - test - docker - deploy variables: DOCKER_IMAGE: mydockerhub/go-server build: stage: build image: golang:1.20 script: - go mod tidy - go build -o server . test: stage: test image: golang:1.20 script: - go test ./... docker: stage: docker image: docker:latest services: - docker:dind script: - docker build -t $DOCKER_IMAGE:latest . - echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin - docker push $DOCKER_IMAGE:latest deploy: stage: deploy script: - ssh user@your-server-ip "docker pull $DOCKER_IMAGE:latest && docker run -d -p 8080:8080 $DOCKER_IMAGE:latest"

Step 4: Configure GitLab CI/CD Variables

In GitLab project settings → CI/CD → Variables, add:

  • CI_REGISTRY_USER → Your Docker Hub username
  • CI_REGISTRY_PASSWORD → Your Docker Hub password or token

Step 5: Deploy to Server

On your Ubuntu server, pull the latest image:

sudo docker pull mydockerhub/go-server:latest

Run the container:

sudo docker run -d -p 8080:8080 mydockerhub/go-server:latest


Best Practices

  • Run tests on every commit to catch errors early
  • Use Docker for consistent builds across environments
  • Automate deployments with GitLab CI/CD pipelines
  • Use staging environments before production deployment
  • Monitor logs and metrics after each deployment

Note: HostPalace offers CI/CD-ready servers with GitLab integration for seamless Go application deployment.