How to Dockerize go (golang) web app

How to Dockerize go web app

In this tutorial I will show you how to dockerize go web app. Go (often referred to as golang) is a programming language created at Google in 2009 by Robert Griesemer, Rob Pike, and Ken Thompson. It is a compiled, statically typed language in the tradition of Algol and C, with garbage collection, limited structural typing, memory safety features and CSP-style concurrent programming features added. The compiler and other language tools originally developed by Google are all free and open source.

Docker is great way to ship and deploy your app easily. I have already created an sample app and hosted it on github. You can feel free to clone the app and use it.

Create a sample app

For this tutorial we will create a hello world sample app. I also have a sample app on github repository.

https://github.com/chetankapoor/go-example.git

You may also like: Notification on slack after completion of Ansible

Create a new file called server.go and open it with your favourite editor.

touch server.go

After creating a file open the file and add the following into the file:

vim server.go

package main

import (
    "fmt"
    "net/http"
)

func helloWorld(w http.ResponseWriter, r *http.Request){
    fmt.Fprintf(w, "Hello World")
}

func main() {
    http.HandleFunc("/", helloWorld)
    http.ListenAndServe(":8080", nil)
}

Now we will run this app using the following command.

go run server.go

Then Open your browser and open http://localhost:8080

You may also like: Create EC2 instance with Ansible

Dockerize the app

Now we start Dockerizing the app.  First of all add Dockerfile in your app directory.

vim Dockerfile

Then paste the following content into Dockerfile:

FROM golang:alpine
RUN mkdir /app
ADD . /app/
WORKDIR /app
EXPOSE 8080
CMD ["go", "run", "/app/server.go"]

Build your app

After creating Dockerfile its time to build your app. You can use docker build command to build the docker image. We will also tag our image with -t option.

docker build -t go-example .
Sending build context to Docker daemon 8.649MB
Step 1/6 : FROM golang:alpine
---> 85256d3905e2
Step 2/6 : RUN mkdir /app
---> Using cache
---> 21be5282c8ae
Step 3/6 : ADD . /app/
---> Using cache
---> 127d4a3a0e37
Step 4/6 : WORKDIR /app
---> Using cache
---> 89e9fa167dd9
Step 5/6 : EXPOSE 8080
---> Using cache
---> 843c4bcbb17e
Step 6/6 : CMD ["go", "run", "/app/server.go"]
---> Using cache
---> 97445d8257e4
Successfully built 97445d8257e4
Successfully tagged go-example:latest

Test your Image

Now its time to test your docker image.

docker run -it -p 8080:8080 go-example

Then Open your browser and open http://localhost:8080

You will see Hello World in your browser.

Please let me know if you like this tutorial.

If you have any issues please feel free to comment below.

Leave a Reply

Your email address will not be published.


*