Set Up CI/CD for Go Applications with Jenkins

CI/CD for Go Applications with Jenkins

Jenkins is a popular open-source automation server that enables Continuous Integration and Continuous Deployment (CI/CD). It can build, test, and deploy Go applications automatically. This guide explains how to set up a CI/CD pipeline for Go using Jenkins and Docker.


Step 1: Install Jenkins

sudo apt update

sudo apt install openjdk-11-jdk -y

wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -

sudo sh -c 'echo deb https://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'

sudo apt update

sudo apt install jenkins -y

Enable and start Jenkins:

sudo systemctl enable jenkins

sudo systemctl start jenkins


Step 2: Install Required Plugins

  • Git Plugin
  • Docker Pipeline Plugin
  • Pipeline Plugin

Step 3: Create a 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 4: Create Jenkins Pipeline (Jenkinsfile)

Create a file named Jenkinsfile in your repository:

pipeline { agent any environment { DOCKER_IMAGE = "mydockerhub/go-server" } stages { stage('Checkout') { steps { git branch: 'main', url: 'https://github.com/your-repo/go-server.git' } } stage('Build') { steps { sh 'go mod tidy' sh 'go build -o server .' } } stage('Test') { steps { sh 'go test ./...' } } stage('Docker Build & Push') { steps { sh 'docker build -t $DOCKER_IMAGE:latest .' sh 'echo $DOCKER_PASSWORD | docker login -u $DOCKER_USERNAME --password-stdin' sh 'docker push $DOCKER_IMAGE:latest' } } stage('Deploy') { steps { sh 'ssh user@your-server-ip "docker pull $DOCKER_IMAGE:latest && docker run -d -p 8080:8080 $DOCKER_IMAGE:latest"' } } } }

Step 5: Configure Jenkins Credentials

In Jenkins → Manage Jenkins → Credentials, add:

  • DOCKER_USERNAME → Your Docker Hub username
  • DOCKER_PASSWORD → Your Docker Hub password or token

Step 6: Run the Pipeline

Commit and push your Jenkinsfile to the repository. Jenkins will automatically build, test, and deploy your Go application whenever changes are pushed to the main branch.


Best Practices

  • Run tests on every commit to catch errors early
  • Use Docker for consistent builds across environments
  • Automate deployments with Jenkins pipelines
  • Use staging environments before production deployment
  • Monitor Jenkins logs for troubleshooting

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