Building a CLI for Managing Docker Images in Go

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting Up Go Environment
  4. Creating a CLI Application
  5. Implementing Docker Image Management
  6. Conclusion

Introduction

In this tutorial, we will learn how to build a Command Line Interface (CLI) application in Go for managing Docker images. We will leverage the power of Go to interact with Docker through its API. By the end of this tutorial, you will be able to build a CLI tool that can perform various operations on Docker images, such as listing, pulling, pushing, and deleting images.

Prerequisites

To follow along with this tutorial, make sure you have the following prerequisites:

  • Basic understanding of Go programming language
  • Docker installed on your machine

Setting Up Go Environment

Let’s start by setting up our Go environment:

  1. Install Go: Visit the official Go website (https://golang.org/dl/) and download the installer for your operating system. Follow the installation instructions to complete the setup.

  2. Verify Installation: Open a terminal and run the following command to verify that Go is installed correctly:

     go version
    

    If Go is installed properly, you will see the version information printed on the console.

  3. Set Go Paths: Go requires the GOPATH environment variable to be set. Create a directory anywhere on your system (e.g., ~/go) and set it as your GOPATH. Add the bin directory inside your GOPATH to your PATH environment variable.

     export GOPATH=~/go
     export PATH=$PATH:$GOPATH/bin
    

    With our Go environment set up, we are ready to create our CLI application.

Creating a CLI Application

  1. Initialize Go Module: Create a new directory for your project and navigate to it in the terminal. Initialize a new Go module using the following command:

     go mod init github.com/your-username/docker-cli
    

    Replace your-username with your GitHub username or any other preferred namespace.

  2. Install Dependencies: We will use the github.com/docker/docker package to interact with Docker’s API. Install this package by executing the following command:

     go get github.com/docker/[email protected]
    
  3. Create Main File: Create a new file named main.go in your project directory. This file will contain the main entry point for our CLI application.

  4. Import Dependencies: Add the necessary import statements to your main.go file:

     package main
        
     import (
     	"fmt"
     	"log"
     	"os"
        
     	"github.com/docker/docker/api/types"
     	"github.com/docker/docker/client"
     )
    
  5. Define Main Function: Define the main function, which will be the entry point of our CLI application. Add the following code:

     func main() {
     	cli, err := client.NewClientWithOpts(client.FromEnv)
     	if err != nil {
     		log.Fatal(err)
     	}
        
     	// Your CLI application code goes here
        
     	err = cli.Close()
     	if err != nil {
     		log.Fatal(err)
     	}
     }
    

    The above code sets up a connection to the Docker API and closes it when the application finishes.

Implementing Docker Image Management

Now that we have our CLI application set up, let’s implement the Docker image management functionality step by step.

Listing Docker Images

Let’s start by implementing the functionality to list Docker images. Add the following code inside the main function:

images, err := cli.ImageList(context.Background(), types.ImageListOptions{})
if err != nil {
	log.Fatal(err)
}

fmt.Println("Docker Images:")
for _, image := range images {
	fmt.Println("-", image.ID)
}

The code above fetches the list of Docker images and prints their IDs to the console.

Pulling Docker Images

Next, let’s implement the functionality to pull Docker images. Add the following code inside the main function:

authConfig := types.AuthConfig{
	Username: "your-username",
	Password: "your-password",
}
authConfigEncoded, _ := json.Marshal(authConfig)

out, err := cli.ImagePull(context.Background(), "ubuntu", types.ImagePullOptions{
	RegistryAuth: base64.URLEncoding.EncodeToString(authConfigEncoded),
})
if err != nil {
	log.Fatal(err)
}

defer out.Close()

io.Copy(os.Stdout, out)

Make sure to replace your-username and your-password with your Docker Hub username and password, respectively. This code pulls the ubuntu image from Docker Hub and streams the output to the console.

Pushing Docker Images

Next, let’s implement the functionality to push Docker images. Add the following code inside the main function:

out, err := cli.ImagePush(context.Background(), "your-username/my-image", types.ImagePushOptions{})
if err != nil {
	log.Fatal(err)
}

defer out.Close()

io.Copy(os.Stdout, out)

Replace your-username and my-image with your Docker Hub username and the image name you want to push. This code pushes the specified Docker image to Docker Hub and streams the output to the console.

Deleting Docker Images

Finally, let’s implement the functionality to delete Docker images. Add the following code inside the main function:

_, err = cli.ImageRemove(context.Background(), "your-image-id", types.ImageRemoveOptions{
	Force:         true,
	PruneChildren: true,
})
if err != nil {
	log.Fatal(err)
}

fmt.Println("Image deleted successfully.")

Replace your-image-id with the ID of the Docker image you want to delete. This code deletes the specified Docker image and prints a success message.

Conclusion

Congratulations! You have successfully built a CLI application in Go for managing Docker images. You have learned how to interact with the Docker API using the github.com/docker/docker package. Feel free to expand upon this application by adding more functionality or enhancing the existing one.

In this tutorial, we covered the basics of creating a CLI application, listing, pulling, pushing, and deleting Docker images. Continue exploring the Go ecosystem to build more powerful and useful tools.

Happy coding!