How to Create and Push a Custom Docker Image to Docker Hub Using a Script

How to Create and Push a Custom Docker Image to Docker Hub Using a Script

Introduction

Docker is an essential tool for developers and DevOps professionals, enabling the creation of lightweight, portable, and self-sufficient containers. In this blog, we'll walk you through the process of creating a custom Docker image using pengbai/docker-supermario as a base image. We'll also provide a script to automate the process of pushing this image to Docker Hub.

Prerequisites

Before we begin, make sure you have the following installed on your system:

Step 1: Create the Dockerfile

The Dockerfile is the blueprint for your Docker image. We'll start by creating a Dockerfile that uses the official pengbai/docker-supermario image as a base and adds a custom configuration.

  1. Create a new directory for your project:

     mkdir my-docker-image
     cd my-docker-image
    
  2. Create a Dockerfile with the following content:

     # Use the official pengbai/docker-supermario as the base image
     FROM pengbai/docker-supermario:latest
    

Since the pengbai/docker-supermario image already includes everything needed to run Super Mario, no additional configuration is required.

Step 2: Build the Docker Image

Now, we'll create a script to build the Docker image. This script will also handle tagging the image and pushing it to Docker Hub.

  1. Create a build_and_push.sh script with the following content:

     #!/bin/bash
    
     # Variables
     IMAGE_NAME="myimg"
     DOCKER_USERNAME="your_dockerhub_username"
     TAG="latest"
    
     # Build the Docker image
     docker build -t $IMAGE_NAME .
    
     # Tag the image for Docker Hub
     docker tag $IMAGE_NAME $DOCKER_USERNAME/$IMAGE_NAME:$TAG
    
     # Push the image to Docker Hub
     docker push $DOCKER_USERNAME/$IMAGE_NAME:$TAG
    
  2. Replace your_dockerhub_username with your actual Docker Hub username in the script.

  3. Make the script executable and run it:

     chmod +x build_and_push.sh
     ./build_and_push.sh
    

Step 3: Verify the Image on Docker Hub

Once the script has completed, log in to your Docker Hub account and verify that the image myimg has been pushed successfully.

Conclusion

Congratulations! You've successfully created a custom Docker image using pengbai/docker-supermario as a base and pushed the image to Docker Hub using a script. This automated process simplifies the deployment of Docker images and ensures consistency across different environments.

Feel free to experiment further by customizing the Dockerfile or adding more functionality to the Docker image. Happy containerizing!


Further Reading

For more in-depth tutorials and insights on Docker and DevOps, check out these resources:

Stay tuned for more tutorials and tips on Docker and DevOps!