Introduction

Docker is a powerful containerization platform, and Go (Golang) is a highly efficient programming language. Combining the two allows you to create lightweight and portable applications. In this guide, we will walk you through the process of building and running a Go application inside a Docker container. Sample code and instructions are provided.


Prerequisites

Before you begin, ensure you have the following prerequisites in place:


Creating a Go Application

Let's start by creating a simple Go application. Open your favorite code editor and create a file named "main.go" with the following Go code:

package main
import "fmt"
func main() {
fmt.Println("Hello, Go Docker Container!")
}

This code defines a basic Go program that prints a message to the console.


Creating a Dockerfile

To run our Go application inside a Docker container, we need to create a Dockerfile that describes the container's environment. Create a file named "Dockerfile" (no file extension) with the following content:

# Use the official Golang image as the base image
FROM golang:1.16
# Set the working directory inside the container
WORKDIR /app
# Copy the Go application code into the container
COPY . .
# Build the Go application
RUN go build -o main
# Define the command to run the Go application
CMD ["./main"]

This Dockerfile uses the official Golang image, sets the working directory, copies the Go application code into the container, builds the application, and defines the command to run it.


Building the Docker Image

With the Dockerfile in place, it's time to build the Docker image. Open your terminal or command prompt, navigate to the directory containing your Go application and the Dockerfile, and run the following command:

docker build -t go-docker-app .

This command builds a Docker image named "go-docker-app" from the current directory ("."). The "-t" flag specifies the image tag.


Running the Docker Container

Now that the Docker image is built, you can run a container based on this image. Use the following command:

docker run go-docker-app

This command starts a Docker container from the "go-docker-app" image. You should see the output "Hello, Go Docker Container!" in your terminal.


Conclusion

Congratulations! You've successfully built and run a Go application inside a Docker container. This combination of Go and Docker allows you to create portable and efficient applications that can be easily deployed in various environments.


Further Resources

To deepen your understanding of Go and Docker, consider these resources: