Operations 6 min read

How to Build and Deploy a Go Application with Jenkins Pipeline

This guide walks through automating a Go project's build, handling private repository credentials, and deploying the compiled binary to a remote server using a Jenkins pipeline, covering project structure, build steps, credential management, and a complete pipeline script.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
How to Build and Deploy a Go Application with Jenkins Pipeline

Automation Process

Typical enterprise automation pulls code from a repository, builds it, pushes artifacts to an artifact repository (e.g., an image registry), runs tests in a test environment, and finally performs remote deployment. The example simplifies this by deploying immediately after build.

Project Structure

The Go project follows a standard layout:

|-- my-app
    |-- .gitignore
    |-- README.md
    |-- LICENSE
    |-- go.mod
    |-- go.sum
    |-- main.go
    |-- pkg
        |-- ...

Project Build

When building a Go project that uses private modules, go mod tidy requires Git credentials. In Jenkins, create a "Username with password" credential where the username is the GitHub username and the password is a GitHub Access Token. In the pipeline, use usernamePassword to expose these as variables.

stage('Build') {
    steps {
        withCredentials(bindings: [
            usernamePassword(credentialsId: 'GITHUB_CREDENTIAL',
                usernameVariable: 'GITHUB_USER',
                passwordVariable: 'GITHUB_ACCESS_TOKEN')
        ]) {
            sh '''
                git config --global url."https://${GITHUB_ACCESS_TOKEN}:[email protected]/".insteadOf "https://github.com/"
                go mod tidy
                go build -o bin/my-app main.go
            '''
        }
    }
}

Remote Deployment

After building, the artifact is normally pushed to an artifact repository and later pulled for deployment. This example skips the repository step and deploys directly. Since the build and production environments differ, the binary is copied to a remote server via SSH.

Configure three Jenkins credentials: DEPLOY_HOST and DEPLOY_PORT as Secret Text, and SSH_CREDENTIAL as SSH Username with private key.

stage('Deploy') {
    environment {
        DEPLOY_HOST = credentials('DEPLOY_HOST')
        DEPLOY_PORT = credentials('DEPLOY_PORT')
    }
    steps {
        withCredentials([
            sshUserPrivateKey(credentialsId: 'SSH_CREDENTIAL',
                keyFileVariable: 'SSH_KEY',
                usernameVariable: 'SSH_USERNAME')
        ]) {
            sh """
                mkdir -p ~/.ssh && chmod 700 ~/.ssh
                echo 'StrictHostKeyChecking no' >> /etc/ssh/ssh_config
                cat ${SSH_KEY} > ~/.ssh/id_rsa && chmod 400 ~/.ssh/id_rsa
                scp -P ${DEPLOY_PORT} bin/my-app ${SSH_USER}@${DEPLOY_HOST}:/data/my-app
                ssh -p ${DEPLOY_PORT} ${SSH_USER}@${DEPLOY_HOST} \"nohup /data/my-app >> /data/my-app.log 2>&1 &\"
            """
        }
    }
}

Deployment steps include:

Copy the built artifact to the deployment server.

Run the deployment command on the server, e.g., nohup /data/my-app >> /data/my-app.log 2>&1 &.

For more complex scenarios, you can place a deployment script (e.g., deploy.sh) on the server and invoke it via SSH.

Complete Jenkins Pipeline

pipeline {
    agent {
        docker {
            image 'golang:1.15-alpine'
            args '-v /data/my-app-cache:/go/.cache'
        }
    }
    options {
        timeout(time: 20, unit: 'MINUTES')
        disableConcurrentBuilds()
    }
    stages {
        stage('Build') {
            steps {
                withCredentials(bindings: [
                    usernamePassword(credentialsId: 'GITHUB_CREDENTIAL',
                        usernameVariable: 'GITHUB_USER',
                        passwordVariable: 'GITHUB_ACCESS_TOKEN')
                ]) {
                    sh '''
                        git config --global url."https://${GITHUB_ACCESS_TOKEN}:[email protected]/".insteadOf "https://github.com/"
                        go mod tidy
                        go build -o bin/my-app main.go
                    '''
                }
            }
        }
        stage('Deploy') {
            environment {
                DEPLOY_HOST = credentials('DEPLOY_HOST')
                DEPLOY_PORT = credentials('DEPLOY_PORT')
            }
            steps {
                withCredentials([
                    sshUserPrivateKey(credentialsId: 'SSH_CREDENTIAL',
                        keyFileVariable: 'SSH_KEY',
                        usernameVariable: 'SSH_USERNAME')
                ]) {
                    sh """
                        mkdir -p ~/.ssh && chmod 700 ~/.ssh
                        echo 'StrictHostKeyChecking no' >> /etc/ssh/ssh_config
                        cat ${SSH_KEY} > ~/.ssh/id_rsa && chmod 400 ~/.ssh/id_rsa
                        scp -P ${DEPLOY_PORT} bin/my-app ${SSH_USER}@${DEPLOY_HOST}:/data/my-app
                        ssh -p ${DEPLOY_PORT} ${SSH_USER}@${DEPLOY_HOST} \"nohup /data/my-app >> /data/my-app.log 2>&1 &\"
                    """
                }
            }
        }
    }
}

Original article: https://juejin.cn/post/6969968007690846238

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ci/cdDeploymentPipelineJenkins
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.