Short Intro to Dockerize Go(lang) REST API

Teofanus Gary
2 min readFeb 28, 2022

Go(lang) is a programming language that’s good to create a backend for web application. We will use Go as the language for a simple REST API that we will Dockerize.

Before we go through over the steps, here’s some reason why you might want to consider dockerizing your REST API:

  • Consistent development environment, using Docker, you and your team can have matching dev environment. This eliminates the problem that arise from using different setup like different version of some dependency. Not only your team, but your production server can also have the same setup as the development setup that you and your team use.
  • Mobility, with Docker, you can run your environment everywhere, on different operating systems, on different hardware, etc.

Now continue to the steps, first we imagine you already have a working simple REST API that uses PostgreSQL as database. You can use this Dockerfile

Here, we use what’s called a multi stage build for our Dockerfile. That means that we are using two images, one for building our source code into a binary and the other images is for hosting our binary. The benefit of this is that the resulting image is much smaller than if we are not using multi stage build.

The commands

  • Line 1–3 setup our build image (which is alpine) and install a certificates.
  • Line 6–7 copy the dependency file of our go rest api source code and download it.
  • Line 9–10 compiles our source code into a binary called ‘myapp’
  • Line 13–18 setup another image and copies our binary from step before and then run it while exposing port 8080.

You can go ahead and build that Dockerfile using docker build myapp . , that command will build our Dockerfile into an image. After it finished, we can run docker run -dp 8080:8080 myapp. Voilla! If there are no problem your app should be up and running. Now, we go to the next step.

You might be wondering how to setup our database, do we need to run another container to host our database? No, you can use docker compose to help you with that. Docker compose is a tool that is used to manage a multi container application. You can see below to see an example docker compose file.

Here we setup 2 services: postgres (our database server)and myapp (our REST API). Our postgres service will pull a postgres image and setup some environment needed (you can configure it with a .env file but we already set a default). Our myapp service, will use our Dockerfile to build an image and since myapp service is dependent to the databasem we use depends_on to make sure the database is ready.

Try running it with docker-compose up . Congrats! You now have a golang REST API and a database.

References

--

--