In the previous post, we learned how to write Go application that using REST API protocol to populate data. In this post, we will see how to deploy that application in Docker container by using Dockerfile.
There are many benefits of deploying app in container compared to traditional deployment such as physical server or virtual machine. Containers are more portable and efficient just to name one of the many benefit of it.
To start deploying app in container, we need to prepare our code app which in this case is main.go. For this tutorial, we will be using REST API app from previous post. Within the same directory, we should create ‘Dockerfile’ file by issuing this command
touch Dockerfile
Now open the Dockerfile using your favorite editor and copy this into the file.
FROM "golang"
COPY . .
RUN go get -u github.com/gorilla/mux
CMD ["go", "run", "main.go"]
Now let’s go through the line. First line is saying that we will be using image from official golang image in docker hub. This is basic image for our container.
What COPY does is it will copy file from current directory to the directory in the container. For more advance use case, the location might be different depending on the application design.
RUN is command that will be run in the container. Example above showing gorilla/mux package is being installed to our container.
CMD is the command the container executes by default when you launch the built image. So when we spin our container, it will execute main.go file.
Once Dockerfile been created, we can start building the container by using this command.
docker build -t go-restapi .
Docker build will start the building process in current directory. -t option is used for naming our container. Once done, we can start the container using this command.
docker run --rm -it -d -p 8000:8000 go-restapi
Use -d option to run it in background. The app will be available at http://<host ip address>:8000
.