This task aims to set up a Jenkins instance running inside a Docker container while ensuring data persistence using Docker volumes. The setup will also include basic security configurations, port mappings, and plugin installations to prepare Jenkins for use in a CI/CD pipeline.
Ensure that Docker and Docker Compose are installed on your system.
sudo apt update
sudo apt install -y docker.io
sudo systemctl enable docker
sudo systemctl start docker
sudo apt install -y docker-compose
docker --version
docker-compose --version
Jenkins stores job data, configuration, and plugins in /var/jenkins_home
. To ensure persistence, create a Docker volume:
docker volume create jenkins_data
To check the created volume:
docker volume ls
For better communication between services (e.g., if using a reverse proxy):
docker network create jenkins_network
Create a directory for Jenkins and navigate into it:
mkdir -p ~/jenkins-docker && cd ~/jenkins-docker
touch docker-compose.yml
Create a
docker-compose.ymlfile:
touch docker-compose.yml
Edit the file and add the following configuration:
version: '3.8'
services:
jenkins:
image: jenkins/jenkins:lts
container_name: jenkins_server
restart: unless-stopped
ports:
- "8080:8080"
- "50000:50000"
volumes:
- jenkins_data:/var/jenkins_home
- /var/run/docker.sock:/var/run/docker.sock
environment:
- JAVA_OPTS=-Djenkins.install.runSetupWizard=false
- JENKINS_OPTS=--prefix=/jenkins
networks:
- jenkins_network
volumes:
jenkins_data:
networks:
jenkins_network:
driver: bridge
jenkins/jenkins:ltsimage is used (latest stable version).
(jenkins_data)ensures data is not lost when restarting the container.
(8080:8080for UI and
50000:50000for agent communication).
JAVA_OPTS(optional).
(/jenkins)for better reverse proxy handling.
Run the following command to start Jenkins:
docker-compose up -d
To check if the container is running:
docker ps
If you need logs:
docker logs -f jenkins_server
Jenkins requires an initial admin password when accessed for the first time.
Run:
docker exec -it jenkins_server cat /var/jenkins_home/secrets/initialAdminPassword
Copy this password and paste it when prompted in the Jenkins UI.
http://:8080/jenkins
Navigate to Manage Jenkins → Plugin Manager → Available Plugins and install:
Create a file named Jenkinsfile in your repository:
pipeline {
agent {
docker {
image 'maven:3.8.1'
}
}
stages {
stage('Checkout') {
steps {
git 'https://github.com/your-repo/sample-app.git'
}
}
stage('Build') {
steps {
sh 'mvn clean package'
}
}
stage('Test') {
steps {
sh 'mvn test'
}
}
stage('Docker Build & Push') {
steps {
sh '''
docker build -t your-dockerhub-user/sample-app .
docker login -u your-dockerhub-user -p your-password
docker push your-dockerhub-user/sample-app
'''
}
}
stage('Deploy') {
steps {
sh 'docker run -d -p 8081:8080 your-dockerhub-user/sample-app'
}
}
}
}
You have now successfully set up Jenkins in a Docker container with persistent storage. This setup ensures that: