Jenkins ist der führende Open-Source-Automatisierungsserver für Continuous Integration und Continuous Deployment. Er ermöglicht automatisierte Builds, Tests und Deployments.
Installation
Docker (empfohlen)
# docker-compose.yml
version: '3'
services:
jenkins:
image: jenkins/jenkins:lts
container_name: jenkins
user: root
ports:
- "8080:8080"
- "50000:50000"
volumes:
- ./jenkins-data:/var/jenkins_home
- /var/run/docker.sock:/var/run/docker.sock
restart: alwaysDebian/Ubuntu
# Java installieren
apt install openjdk-17-jdk
# Jenkins Repository
curl -fsSL https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key | tee /usr/share/keyrings/jenkins.asc > /dev/null
echo "deb [signed-by=/usr/share/keyrings/jenkins.asc] https://pkg.jenkins.io/debian-stable binary/" | tee /etc/apt/sources.list.d/jenkins.list
# Installieren
apt update
apt install jenkins
# Starten
systemctl enable --now jenkinsInitiales Setup
# Admin-Passwort anzeigen
cat /var/lib/jenkins/secrets/initialAdminPassword
# Bei Docker
docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPasswordWeb-Setup
1. http://server:8080 öffnen
2. Initiales Passwort eingeben
3. Plugins installieren (vorgeschlagene)
4. Admin-User erstellen
5. Jenkins URL konfigurierenWichtige Plugins
Empfohlene Plugins
- Pipeline (Pipeline-Jobs)
- Git (Git-Integration)
- Docker Pipeline (Docker in Pipelines)
- Blue Ocean (Moderne UI)
- Credentials (Credential-Management)
- SSH Agent (SSH-Schlüssel)
- Slack Notification (Benachrichtigungen)
- Ansible (Ansible-Integration)Plugin installieren
Manage Jenkins → Plugins → Available plugins
→ Plugin suchen und installierenFreestyle Job
Job erstellen
1. New Item → Freestyle project
2. Name eingeben
3. Source Code Management: Git
4. Repository URL eingeben
5. Build Triggers konfigurieren
6. Build Steps hinzufügenBuild Steps
# Execute Shell
#!/bin/bash
cd $WORKSPACE
npm install
npm test
npm run buildPost-Build Actions
- Archive artifacts
- Publish test results
- Email notification
- Deploy to serverPipeline (Jenkinsfile)
Grundstruktur
// Jenkinsfile
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'npm install'
sh 'npm run build'
}
}
stage('Test') {
steps {
sh 'npm test'
}
}
stage('Deploy') {
steps {
sh 'npm run deploy'
}
}
}
post {
success {
echo 'Build succeeded!'
}
failure {
echo 'Build failed!'
}
}
}Mit Umgebungsvariablen
pipeline {
agent any
environment {
NODE_ENV = 'production'
APP_VERSION = '1.0.0'
}
stages {
stage('Build') {
steps {
sh 'echo "Building version ${APP_VERSION}"'
sh 'npm run build'
}
}
}
}Mit Parametern
pipeline {
agent any
parameters {
string(name: 'BRANCH', defaultValue: 'main', description: 'Branch to build')
choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'prod'], description: 'Deploy environment')
booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests?')
}
stages {
stage('Checkout') {
steps {
git branch: "${params.BRANCH}", url: 'https://github.com/user/repo.git'
}
}
stage('Test') {
when {
expression { params.RUN_TESTS == true }
}
steps {
sh 'npm test'
}
}
stage('Deploy') {
steps {
sh "deploy.sh ${params.ENVIRONMENT}"
}
}
}
}Docker in Pipeline
Docker Build
pipeline {
agent any
stages {
stage('Build Docker Image') {
steps {
script {
docker.build("myapp:${env.BUILD_NUMBER}")
}
}
}
stage('Push to Registry') {
steps {
script {
docker.withRegistry('https://registry.example.com', 'docker-credentials') {
docker.image("myapp:${env.BUILD_NUMBER}").push()
docker.image("myapp:${env.BUILD_NUMBER}").push('latest')
}
}
}
}
}
}Docker Agent
pipeline {
agent {
docker {
image 'node:18'
args '-v $HOME/.npm:/root/.npm'
}
}
stages {
stage('Build') {
steps {
sh 'npm install'
sh 'npm run build'
}
}
}
}Multibranch Pipeline
Konfiguration
1. New Item → Multibranch Pipeline
2. Branch Sources: Git
3. Repository URL eingeben
4. Credentials konfigurieren
5. Scan Multibranch Pipeline TriggersBranch-spezifisch
pipeline {
agent any
stages {
stage('Deploy Staging') {
when {
branch 'develop'
}
steps {
sh 'deploy-staging.sh'
}
}
stage('Deploy Production') {
when {
branch 'main'
}
steps {
sh 'deploy-production.sh'
}
}
}
}Credentials
Credentials hinzufügen
Manage Jenkins → Credentials → System → Global credentials → Add Credentials
Types:
- Username with password
- SSH Username with private key
- Secret text
- Secret fileIn Pipeline verwenden
pipeline {
agent any
stages {
stage('Deploy') {
steps {
withCredentials([
usernamePassword(
credentialsId: 'deploy-credentials',
usernameVariable: 'USER',
passwordVariable: 'PASS'
)
]) {
sh 'sshpass -p $PASS ssh $USER@server deploy.sh'
}
}
}
stage('Git Push') {
steps {
withCredentials([sshUserPrivateKey(
credentialsId: 'git-ssh-key',
keyFileVariable: 'SSH_KEY'
)]) {
sh 'GIT_SSH_COMMAND="ssh -i $SSH_KEY" git push origin main'
}
}
}
}
}Webhooks
GitHub Webhook
GitHub Repository → Settings → Webhooks → Add webhook
Payload URL: https://jenkins.example.com/github-webhook/
Content type: application/json
Events: Just the push eventJenkins Job konfigurieren
Job → Configure → Build Triggers
→ GitHub hook trigger for GITScm pollingGitLab Webhook
GitLab Project → Settings → Webhooks
URL: https://jenkins.example.com/project/job-name
Secret Token: (von Jenkins)
Trigger: Push eventsShared Libraries
Library-Struktur
jenkins-shared-library/
├── vars/
│ └── myBuild.groovy
├── src/
│ └── org/
│ └── mycompany/
│ └── Utils.groovy
└── resources/
└── templates/vars/myBuild.groovy
def call(Map config = [:]) {
pipeline {
agent any
stages {
stage('Build') {
steps {
sh "npm install"
sh "npm run build"
}
}
}
}
}Library einbinden
@Library('my-shared-library') _
myBuild()Blue Ocean
Installation
Manage Jenkins → Plugins → Available
→ "Blue Ocean" installierenZugriff
http://jenkins:8080/blueFeatures
- Moderne UI
- Pipeline-Editor
- Branch-Visualisierung
- Pull Request IntegrationAgents (Nodes)
SSH-Agent hinzufügen
Manage Jenkins → Nodes → New Node
Name: build-agent
Remote root directory: /var/jenkins
Launch method: Launch agents via SSH
Host: agent.example.com
Credentials: SSH keyAgent in Pipeline
pipeline {
agent {
label 'docker-agent'
}
stages {
stage('Build') {
steps {
sh 'docker build -t myapp .'
}
}
}
}
// Oder mit mehreren Agents
pipeline {
agent none
stages {
stage('Build') {
agent { label 'build' }
steps {
sh 'make build'
}
}
stage('Test') {
agent { label 'test' }
steps {
sh 'make test'
}
}
}
}Notifications
pipeline {
agent any
post {
failure {
mail to: 'team@example.com',
subject: "Build Failed: ${env.JOB_NAME}",
body: "Check console output at ${env.BUILD_URL}"
}
}
}Slack
pipeline {
agent any
post {
success {
slackSend channel: '#builds',
color: 'good',
message: "Build Successful: ${env.JOB_NAME} #${env.BUILD_NUMBER}"
}
failure {
slackSend channel: '#builds',
color: 'danger',
message: "Build Failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}"
}
}
}Backup
Jenkins Backup
#!/bin/bash
# /usr/local/bin/jenkins-backup.sh
JENKINS_HOME="/var/lib/jenkins"
BACKUP_DIR="/backup/jenkins"
DATE=$(date +%Y%m%d)
mkdir -p $BACKUP_DIR
# Wichtige Dateien sichern
tar -czf "$BACKUP_DIR/jenkins_$DATE.tar.gz" \
$JENKINS_HOME/config.xml \
$JENKINS_HOME/jobs \
$JENKINS_HOME/users \
$JENKINS_HOME/secrets \
$JENKINS_HOME/nodes \
$JENKINS_HOME/*.xml
# Alte Backups löschen
find $BACKUP_DIR -mtime +30 -deleteZusammenfassung
| Komponente | Beschreibung | |------------|--------------| | Freestyle Job | Einfache GUI-basierte Jobs | | Pipeline | Code-basierte Jobs (Jenkinsfile) | | Multibranch | Automatische Branch-Erkennung | | Blue Ocean | Moderne UI |
| Port | Dienst | |------|--------| | 8080 | Web Interface | | 50000 | Agent Communication |
| Plugin | Funktion | |--------|----------| | Pipeline | Pipeline-Jobs | | Git | Git-Integration | | Docker Pipeline | Docker-Support | | Blue Ocean | Moderne UI |
Fazit
Jenkins ist extrem flexibel und lässt sich an praktisch jede CI/CD-Anforderung anpassen. Jenkinsfiles (Pipeline as Code) ermöglichen versionierte und reproduzierbare Builds. Mit Docker-Agents und Shared Libraries wird die Wartung größerer Jenkins-Installationen handhabbar. Für eine moderne Entwicklererfahrung empfiehlt sich Blue Ocean als Frontend.