Building an Golang App Docker Image with Dockerfile

Introduction

Dockerfile is a script that having the command and while deployment the docker image container We will get up and running service which configured with commands.

Prerequisites

  • Basic knowledge of Docker.
  • Basic knowledge of Linux commands.

Step 1: Create a Golang Directory

To begin, we set up a directory just for Golang-related files by employing the mkdir command.

mkdir golang

Step 2: Create a Dockerfile

Now that we have created a folder, we can use the nano editor to create a Dockerfile within that folder:

nano Dockerfile

Paste the following commands.

FROM golang:latest

WORKDIR /app

COPY . .

RUN go build -o main .

EXPOSE 8080

CMD ["./main"]

Save and exit from the nano text editor.

This Dockerfile uses the latest version of the official Golang image as the base image. The WORKDIR command sets the current working directory to /app. The COPY command copies all the files from the host machine to the container. The RUN command runs the go build command to build the Go application. The -o flag specifies the name of the output file, and the “.” argument specifies the current directory as the location of the source files. The EXPOSE command tells Docker that the container will listen on port 8080. The CMD command runs the compiled binary file of the Go application.

You may want to adjust the command according to your needs and also this is a basic setup for running a Go app with no additional configurations.

Step 3: Building Golang Docker Image

The docker build command is now used to construct the Dockerfile. within which we give our image a custom name (such as golang_image) and tag it with the 1.0.0 suffix.

docker build -t golang_image:1.0.0 .

The docker images command should be used to verify the image’s existence after it has been constructed.

We can see a list of all the images that have been created or obtained from any public or private registry using the docker images command.

Step 4: Deploy Golang App Container

Run the image locally as a container after it has been built:

We use detached mode to run the container continuously in the background. In the docker run command, include -d.
We provide port 8080. To have the server run on localhost, use -p 8080:8080.
As a result, the docker run command also uses the image and the tag that goes with it as input to run the container.

docker run --name custom_golang -d -p 8080:8080 golang_image:1.0.0

Step 5: Testing Go Lang App Test Page

Go to any local browser and type localhost to see if the Apache server is present.

http://localhost:8080

Conclusion

We have successfully build Golang custom image from scratch dockerfile on ubuntu 22.04 LTS, If you still have questions, please post them in the comments section below.

Author

Building an Golang App Docker Image with Dockerfile

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top