Building and Pushing Docker Images with Jenkins

One of the most powerful use cases for Jenkins is to automate Docker workflows. As a DevOps engineer, building and pushing Docker images manually wastes time—let’s fix that.

In this tutorial, you’ll learn how to create a Jenkins job that:

  1. Pulls code from GitHub
  2. Builds a Docker image
  3. Pushes it to Docker Hub

🧰 Prerequisites

Before we begin, make sure:

✅ Jenkins is installed and running
✅ Docker is installed on the Jenkins host
✅ Your Jenkins user has Docker permissions
✅ You have a Docker Hub account and credentials ready


✅ Step 1: Give Jenkins Access to Docker

If you’re on Ubuntu:

sudo usermod -aG docker jenkins
sudo systemctl restart jenkins

Then restart your system or Jenkins service.


✅ Step 2: Store Docker Hub Credentials in Jenkins

  1. Go to Jenkins > Manage Jenkins > Credentials
  2. Add new credentials:
    • Kind: Username & Password
    • ID: dockerhub-creds
    • Username: Your Docker Hub username
    • Password: Your Docker Hub password or token

✅ Step 3: Create a Jenkins Job

  1. Go to Jenkins > New Item > Freestyle project
  2. Name it docker-image-build-push
  3. Under Source Code Management, add your GitHub repo URL
    (The repo should contain a Dockerfile)
  4. Under Build Environment, check Use secret text or file
  5. Under Build Steps, choose “Execute shell” and add:
#!/bin/bash

# Variables
IMAGE_NAME=yourdockerhubusername/myapp:latest

echo "Logging into Docker Hub..."
echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin

echo "Building Docker image..."
docker build -t $IMAGE_NAME .

echo "Pushing image to Docker Hub..."
docker push $IMAGE_NAME

echo "Done!"

Replace yourdockerhubusername/myapp with your actual repo name.


🧪 Step 4: Trigger the Job

  • Push a code change to GitHub
  • Or click “Build Now” in Jenkins
  • Monitor the Console Output for build and push logs

📦 Result

Your Docker image will now be available at:

https://hub.docker.com/repository/docker/yourdockerhubusername/myapp

🎉 That’s a fully automated build pipeline!


🔐 Security Tip

Use Docker Hub tokens instead of your password if possible.
Regenerate tokens from your Docker Hub account under Security > Access Tokens.


🔗 Internal Links


🔗 External Links


✅ Conclusion

With Jenkins + Docker, your CI/CD pipeline becomes lightning-fast and repeatable. You’ve just automated one of the most common DevOps tasks—building and pushing Docker images to a registry.

In the next post, we’ll explore how to deploy these images to Kubernetes or an EC2 server automatically.

Leave a Comment

Your email address will not be published. Required fields are marked *