The Wayback Machine - https://web.archive.org/web/20240914230744/https://www.geeksforgeeks.org/how-to-dockerize-a-golang-application/
Open In App

How to Dockerize a Golang Application?

Last Updated : 30 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Docker is a containerization platform that lets you build, run, and manage applications in an isolated environment. In a container, software, libraries, and configuration files are bundled together and isolated from one another. Golang is an open-source, procedural, and statically typed programming language. In this article, we’ll discuss how to develop and deploy a Golang application using Docker.

Dockerizing a Golang application

As part of this tutorial, we will create a simple Golang application that acts as a REST API.

Step 1: Run the following commands to create a new Golang project.

$ mkdir docker-go

$ cd docker-go

$ go mod init dockergo

 

Step 2: Paste the following into a new file main.go

$ touch main.go

Go




package main
  
// Importing http and mux package
import (
    "encoding/json"
    "log"
    "net/http"
    "github.com/gorilla/mux"
)
  
func main() 
{
    // Creating a new router instance
    router := mux.NewRouter()
      
    // Creating a new controller to handle response
    // for '/' endpoint
    router.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) 
    {
          
        response := map[string]string{
            "response": "Dockerizing Go Application",
    }
          
    // Setting the response
    json.NewEncoder(rw).Encode(response)
})
      
// Logging on console
log.Println("⚡ïļ[bootup]: Server is running at port: 5000")
      
      
http.ListenAndServe(":5000", router)
// starting the server on port 5000
}


Step 3: You can start the application by running

$ go run main.go

 

Project Structure: This is how the project structure should look at this point.

 

Dockerfile for development: Create a Dockerfile for the development phase of our react project. Let’s name it Dockerfile.dev.

$ touch Dockerfile.dev

 

Step 4: In the newly created file, paste the following commands

# Latest golang image on apline linux
FROM golang:1.17-alpine

# Work directory
WORKDIR /docker-go

# Installing dependencies
COPY go.mod go.sum ./
RUN go mod download

# Copying all the files
COPY . .

# Starting our application
CMD ["go", "run", "main.go"]

# Exposing server port
EXPOSE 5000

Step 5: Now create a docker image by using the docker build command

$ docker build -f Dockerfile.dev -t [name:tag] .

Here,

  • -f: Path to the docker file
  • -t: Name and tag for the image
  • .: Context for the build process

Once the build process has been completed, you will receive the id and tag of your new image.

 

Step 6: Create a docker container by running

$ docker run -d -it –-rm -p [host_port]:[container_port] --name [container_name] [image_id/image_tag]

 

Here,

  • -d: Run container in background and print container ID
  • -it: Create an interactive container
  • -p: Map host port to container port
  • –name: Assign a name to the container
  • –rm: Remove the container when it exits.

Step 7: Verify whether the container has been created successfully by running

$ docker container ps

 

Step 8: Navigate to http://localhost:5001/  to verify the build process.

 

Dockerfile for production: By looking at the docker images, you will see that our simple go application takes up half a GB of space. So, we will reduce the size of our image for production deployments.

$ docker images

 

Step 9: The next step is to create a Dockerfile for production mode.

$ touch Dockerfile

 

# Latest golang image on apline linux
FROM golang:1.17 as builder

# Env variables
ENV GOOS linux
ENV CGO_ENABLED 0

# Work directory
WORKDIR /docker-go

# Installing dependencies
COPY go.mod go.sum ./
RUN go mod download

# Copying all the files
COPY . .

# Building the application
RUN go build -o docker-go

# Fetching the latest nginx image
FROM alpine:3.16 as production

# Certificates
RUN apk add --no-cache ca-certificates

# Copying built assets from builder
COPY --from=builder docker-go .

# Starting our application
CMD ./docker-go

# Exposing server port
EXPOSE 5000

Step 10: Build an image and create a container using the updated Dockerfile.

$ docker build -t [name:tag] .

 

 

$ docker run -d -it -–rm -p [host_port]:[container_port] –name [container_name] [image_id/image_tag]

 

Step 11: The application’s size has now been reduced to just 13MB.

$ docker images

 

Step 12: Browse to http://localhost:5002/ to view the dockerized golang application.

 

Project Structure: This is how the project structure should look at this point.

 

Note: Please refer to the Dockerfile used in this tutorial if you have difficulties following the above steps.



Similar Reads

How to Dockerize django application for production deployment with Gunicorn and Nginx
Docker is an open-source containerization platform used for building, running, and managing applications in an isolated environment. A container is isolated from another and bundles its software, libraries, and configuration files. Django is an open-source Python web framework that can be used to quickly develop fully functional web applications. I
5 min read
Dockerize Spring Boot Application With PostgresSQL
In recent years, Docker has revolutionized the way in which we deploy and manage applications, offering a lightweight and productive solution for packaging software and its conditions into containers. For developers working with Spring Boot, a well known Java system for building undertaking grade applications, Dockerization gives various advantages
8 min read
Dockerize Spring Boot Application with MySQL
Spring boot is the most modern framework used for building microservice-based applications today. Deploying spring boot applications requires multiple steps which require complex infrastructure and tools. Docker helps with the easy deployment of spring boot applications with the help of containers. So let's see how we can dockerize a spring boot ap
4 min read
How to Dockerize Angular Application
Dockerizing an Angular application involves packaging it into a Docker container, which can simplify deployment and ensure consistency across different environments. Docker is a containerization platform that allows you to package applications and their dependencies into lightweight, portable containers. The Docker containers can run on any machine
5 min read
How to Dockerize an ExpressJS App ?
Docker is an open-source containerization platform used for building, running, and managing applications in an isolated environment. A container is isolated from another and bundles its software, libraries, and configuration files. This article will discuss how to dockerize an Express app for the development and deployment phases. Prerequisites: Be
4 min read
How to Dockerize a ReactJS App ?
Dockerizing the application refers to putting the application and all related items inside a docker container. It makes the deployment easier, and scale better with the help of small containers. Docker is an open-source containerization platform used for building, running, and managing applications in an isolated environment. A container is isolate
4 min read
How to convert a slice of bytes in uppercase in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to convert a slice in the uppercase usin
2 min read
Golang program that uses fallthrough keyword
With the help of fallthrough statement, we can use to transfer the program control just after the statement is executed in the switch cases even if the expression does not match. Normally, control will come out of the statement of switch just after the execution of first line after match. Don't put the fallthrough in the last statement of switch ca
2 min read
math.Lgamma() Function in Golang with Examples
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. This package provides Lgamma() function which is used to find the natural logarithm and sign (either -1 or +1) of Gamma(a). So, you need to add a math package in your program with the help of th
2 min read
math.Float64bits() Function in Golang With Examples
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. This package provides Float64bits() function which returns the IEEE 754 binary representation of a with the sign bit of a and the result in the same bit position. So, you need to add a math pack
2 min read
How to check equality of slices of bytes in Golang?
In Go language slice is more powerful, flexible, and convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence that stores elements of a similar type, you are not allowed to store different types of elements in the same slice. In the Go slice of byes, you are allowed to check the equality of the slices w
3 min read
atomic.AddInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddInt64() function in Go language is used to automatically add delta to the *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax
3 min read
atomic.StoreInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The StoreInt64() function in Go language is used to atomically store val into *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax: f
2 min read
reflect.FieldByIndex() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.FieldByIndex() Function in Golang is used to get the nested field corresponding to index. To access this function, one needs to imports the reflect package in the
2 min read
strings.Contains Function in Golang with Examples
strings.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false. Syntax: func Contains(str, substr string) bool Here, str is the original string and substr is the string that you want to check. Let us discuss th
2 min read
bits.Sub() Function in Golang with Examples
The bits.Sub() Function in Golang is used to find the difference of a, b and borrow, i.e. diff = a - b - borrow. Here the borrow must be 0 or 1; otherwise, the behavior is undefined. To access this function, one needs to imports the math/bits package in the program. The return value of the borrowOutput will be always 0 or 1 in any case. Syntax: fun
2 min read
How to convert a slice of bytes in lowercase in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to convert a slice in the lowercase usin
2 min read
io.PipeWriter.CloseWithError() Function in Golang with Examples
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The PipeWriter.CloseWithError() function in Go language is used to close the writer. However, successive reads from the PipeReader i.e, read half of the pipe will not return any
3 min read
Import in GoLang
Pre-requisite learning: Installing Go on Windows / Installing Go on MacOS Technically defining, a package is essentially a container of source code for some specific purpose. This means that the package is a capsule that holds multiple elements of drug/medicine binding them all together and protecting them in one mini shell. This capsule is easy to
9 min read
time.Round() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Round() function in Go language is used to find the outcome of rounding the stated duration 'd' to the closest multiple of 'm' duration. Here, the rounding manner for middle values is to round far off from 0. Moreover, this function is defined under th
2 min read
How to add a method to struct type in Golang?
Structs consist of data, but apart from this, structs also tell about the behavior in the form of methods. Methods attached to structs is very much similar to the definition of normal functions, the only variation is that you need to additionally specify its type. A normal function returning an integer and taking no parameter would look like. func
3 min read
Converting a string variable into Boolean, Integer or Float type in Golang
Various types of string conversions are needed while performing tasks in Golang. Package strconv is imported to perform conversions to and from string. String to Boolean Conversion ParseBool is used to convert string to boolean value. It accepts 1, t, T, TRUE, true, True as true and 0, f, F, FALSE, false, False as false. Any other value returns an
3 min read
Check if the given slice is sorted in Golang
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In Go language, you can check the given slice is sorted or not with the help of Sl
3 min read
How to compare times in Golang?
With the help of Before() and After() and Equal(), function we can compare the time as well as date but we are also going to use the time.Now() and time.Now().Add() function for comparison. Functions Used: These functions compares the times as seconds. Before(temp) - This function is used to check if the given time is before the temporary time vari
2 min read
reflect.AppendSlice() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.AppendSlice() Function in Golang is used to appends a slice t to a slice s. To access this function, one needs to imports the reflect package in the program. Synta
2 min read
How to Deploy a Golang WebApp to Heroku?
Go, also known as "Golang," is gaining popularity among DevOps professionals in recent years. There are many tools written in Go, including Docker and Kubernetes, but they can also be used for web applications and APIs. While Golang can perform as fast as a compiled language, coding in it feels more like interpreting with standard tools such as a c
5 min read
reflect.ChanOf() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.ChanOf() Function in Golang is used to get the channel type with the given direction and element type, i.e., t represents int, ChanOf(RecvDir, t) represents <-c
1 min read
flag.Bool() Function in Golang With Examples
Go language provides inbuilt support for command-line parsing and has functions that could be used to define flags to be used with a command-line program using the flag package. This package provides the flag.Bool() function which is used to define a boolean flag with the specified name, default value, and usage string. Syntax: func Bool(name strin
2 min read
time.Sleep() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package. He
3 min read
time.Time.Year() Function in Golang with Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Year() function in Go language is used to find the year in which the specified "t" happens. Moreover, this function is defined under the time package. Here, you need to import the "time" package in order to use these functions. Syntax: func (t Tim
2 min read