Jenkins Container Deployment with Docker and CI/CD Pipeline Setup
Running Jenkins in Docker
Start Jenkins container witth the following command:
docker run -d \
--name jenkins-server \
-p 8080:8080 \
-p 50000:50000 \
-v /opt/jenkins/data:/var/jenkins_home \
-v /var/run/docker.sock:/var/run/docker.sock \
-v $(which docker):/usr/local/bin/docker \
-e TZ=UTC \
jenkins/jenkins:lts
Directory Setup and Permissions
Configure host directory permissions:
# Create and set up Jenkins data directory
sudo mkdir -p /opt/jenkins/data
sudo chown -R 1000:1000 /opt/jenkins/data
sudo chmod -R 755 /opt/jenkins/data
CI/CD Pipeline Configurasion
Define the pipeline script:
pipeline {
agent any
environment {
DOCKER_IMAGE = "myapp"
VERSION = "${env.BUILD_NUMBER}"
REGISTRY_AUTH = 'registry-credentials'
}
stages {
stage('Source Code') {
steps {
git branch: 'main',
credentialsId: 'git-access',
url: 'https://github.com/user/repository.git'
}
}
stage('Build Application') {
steps {
script {
docker.image('mcr.microsoft.com/dotnet/sdk:6.0').inside('-u root -v /var/jenkins_home/workspace:/workspace') {
dir('src') {
sh 'dotnet restore'
sh 'dotnet build -c Release'
sh 'dotnet publish -c Release -o output'
}
}
}
}
}
stage('Containerize and Upload') {
steps {
script {
docker.withRegistry('https://registry.example.com', "${REGISTRY_AUTH}") {
def containerImage = docker.build("${DOCKER_IMAGE}:${VERSION}", "./")
containerImage.push()
}
}
}
}
}
}
Automated Deployment Stage
Add deployment stage for automatic updates:
stage('Deploy to Server') {
steps {
script {
sh """
docker stop running-app || true
docker rm running-app || true
docker pull ${DOCKER_IMAGE}:${VERSION}
docker run -d \
--name running-app \
--restart unless-stopped \
-p 80:8080 \
${DOCKER_IMAGE}:${VERSION}
"""
}
}
}
For producsion servers, simply pull and run the latest container image.