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.
Ensure your Go app builds correctly:
go build server.go
Run tests locally:
go test ./...
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"]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"In GitLab project settings → CI/CD → Variables, add:
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
Note: HostPalace offers CI/CD-ready servers with GitLab integration for seamless Go application deployment.