Dockerizing a Go Application: A Step-by-Step Guide
Why Dockerize Your App?
Docker is an open-source project that allows developers to package their applications with all necessary dependencies, configurations, and scripts inside a container. This approach offers several advantages over traditional virtual machines, including:
- Efficient resource usage: Docker containers use a single host operating system, eliminating the need for multiple guest OSes.
- Improved portability: Docker containers are highly portable and can run on any host operating system.
- Simplified deployment: Docker containers automate the deployment process, making it easier to deploy applications in different environments.
Prerequisites
Before we begin, make sure you have the following:
- Basic Go knowledge: Familiarity with the Go programming language is assumed.
- Docker installed: Install Docker on your machine if you haven’t already.
- A code editor: Choose a code editor, such as Visual Studio Code, to edit your files.
Setting Up Our Development Environment
To get started, we need to install the following:
- Go version ≥ 1.16: Download and install the latest version of Go.
- Docker running locally: Follow the instructions to download and install Docker.
- An IDE or text editor: Choose a code editor to edit your files.
Creating a Minimal Go Project
Create a new folder for your project and navigate into it. Run the following command to create a new Go module:
go mod init myproject
Create a file named main.go
and paste the following code into it:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Run the following command to test your code:
go run .
An Intro to Dockerfiles
A Dockerfile is a text file that contains instructions for building a Docker image. Create a new file named Dockerfile
in the root of your project and add the following lines:
FROM golang:1.16-alpine
WORKDIR /app
COPY go.mod ./
RUN go mod download
COPY . .
RUN go build -o main .
CMD ["./main"]
Let’s break down what each line does:
FROM golang:1.16-alpine
: Uses the official Go 1.16 Alpine image as a base.WORKDIR /app
: Sets the working directory to/app
.COPY go.mod ./
: Copies thego.mod
file into the current directory.RUN go mod download
: Downloads the dependencies specified ingo.mod
.COPY . .
: Copies the current directory into the container.RUN go build -o main .
: Builds the Go program and outputs it tomain
.CMD ["./main"]
: Sets the default command to run when the container starts.
Building the Docker Image
Run the following command to build the Docker image:
docker build -t myproject .
Running the Docker Image
Run the following command to start a new container from the image:
docker run myproject
You should see the output Hello, World!
in your terminal.