Table of Contents

Introduction

Do you find getting started with Docker intimidating? Do you want to take the first step and successfully dockerize golang application? Are you having trouble finding a basic step-by-step tutorial to dockerize golang application? All these questions and just one answer – If yes, you’ve chosen the correct tutorial!

The purpose of this tutorial is to get your hands on Docker for the starters. In this guideline, we will build a ‘Hello, World’ application and follow simple steps to dockerize the golang app. Without further ado, let’s get started with our tutorial.

Prerequisites to Dockerize Golang Application

Before building the application, make sure your system is installed with docker and golang. If not, then visit the links below to install.
⦿ Install Docker
⦿ Install Golang

Project Setup

First of all, let’s create the main.go file and initialize the application using the command go mod init

Our project structure will look like this-

sample-dockerize-app
|– main.go
|– Dockerfile

Our main.go will contain the following code.

Copy Text
package main
 
import (
 "encoding/json"
 "fmt"
 "log"
 "net/http"
 
 "github.com/gorilla/mux"
)
 
func main() {
 router := mux.NewRouter()
 router.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
   response := map[string]string{
     "message": "Welcome to Dockerized app",
   }
   json.NewEncoder(rw).Encode(response)
 })
 
 router.HandleFunc("/{name}", func(rw http.ResponseWriter, r *http.Request) {
   vars := mux.Vars(r)
   name := vars["name"]
   var message string
   if name == "" {
     message = "Hello World"
   } else {
     message = "Hello " + name
   }
   response := map[string]string{
     "message": message,
   }
   json.NewEncoder(rw).Encode(response)
 })
 
 log.Println("Server is running!")
 fmt.Println(http.ListenAndServe(":8081", router))
}

Create a Docker Image

As the Docker documentation says-

An image includes everything needed to run an application- the code or binary, runtimes, dependencies, and any other filesystem objects required.

An image consists of your app definition and everything needed to run the application in the simplest terms.

For creating a docker image, you need to write steps in the config file. The conventional and most preferred file name is Dockerfile, but you can use any name of your choice. However, in my opinion, it’s always better to follow standards.

Now, create a file named Dockerfile and write the following code.

Copy Text
# Build Stage
# First pull Golang image
FROM golang:1.17-alpine as build-env
 
# Set environment variable
ENV APP_NAME sample-dockerize-app
ENV CMD_PATH main.go
 
# Copy application data into image
COPY . $GOPATH/src/$APP_NAME
WORKDIR $GOPATH/src/$APP_NAME
 
# Budild application
RUN CGO_ENABLED=0 go build -v -o /$APP_NAME $GOPATH/src/$APP_NAME/$CMD_PATH
 
# Run Stage
FROM alpine:3.14
 
# Set environment variable
ENV APP_NAME sample-dockerize-app
 
# Copy only required data into this image
COPY --from=build-env /$APP_NAME .
 
# Expose application port
EXPOSE 8081
 
# Start app
CMD ./$APP_NAME

Once done with the file, run the below command to update your application’s dependencies

Copy Text
go mod tidy

Build and Run Docker Image

Use the below command to build the docker image.

Copy Text
docker build --rm -t golang-docker-example .

After executing the command successfully your screen will display following output.

Build and Run the Docker Image

This command will build the image and tag it with the name golang-docker-example. For now, it will just build the image and won’t do anything. The next time would be running the image for handling requests. The running image is what we call a container.

Use the following command to run the image.

Copy Text
docker run -p 8081:8081 golang-docker-example

Successfully executed!

Build and Run the Docker Image

The -p flag is used for defining the port binding. Our application inside the container will be running on the 8081 port and we will bind it to the host port, i.e., 8081. You can use a different port to bind as well. For that, you can run -p $HOST_PORT:8081, for example -p 3000:8081.

Once you are done, Voila! Your application will be running on port 8081. You have now successfully dockerized golang app. Open the browser and hit http://localhost:8081 to check your application.

Your browser will display

Dockerized apps

You can also run http://localhost:8081/{name}* and replace {name}* with anything that will print the message having the variable.

Golang docker example

Source Code: Golang Docker Example Github

You can run the below command to clone the github repo to play around with the code, and feel free to visit the golang docker example github.

git clone https://github.com/DekivadiyaKishan/golang-docker-example.git

Conclusion

So, this was a beginner tutorial on how to dockerize golang application. I hope the tutorial has helped you to at least get started with Docker. If you are a Golang enthusiast and want to explore Golang, please visit the Golang tutorials page.

If you are looking for a skilled developer who can help you with your project requirements, contact Bacancy and hire golang developer

Hire Golang Developer

Connect Now

Build Your Agile Team

Hire Skilled Developer From Us

Subscribe for
weekly updates

newsletter

What Makes Bacancy Stand Out?

  • Technical Subject Matter Experts
  • 2500+ Projects Completed
  • 90% Client Retention Ratio
  • 12+ Years of Experience

Our developers primarily focus on navigating client's requirements with precision. Besides, we develop and innovate to deliver only the best solutions to our clients.

get in touch
[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?