2. Create a docker image

From the Docker documentation:

An image includes everything needed to run an application — the code or binary, runtimes, dependencies, and any other filesystem objects required.

Or put simply, an image is how you define your application and everything it needs to run.

To create a Docker image, you must specify the steps in a configuration file. The default and convenient file name is Dockerfile but you can name it whatever you like. However, following the standard is always a good idea. So create a file called Dockerfile and fill it with the following content.

Explanation

FROM

We are creating our image using the base image golang:alpine . This is basically an image just like what we want to create and is available for us on a Docker repository. This image runs the alpine Linux distribution which is small in size and has Golang already installed which is perfect for our use case. There are tons of publicly available Docker image, have a look at https://hub.docker.com/_/golang

ENV

We also set the environment variable GO111MODULE but what does that even means? If you are unfamiliar with this, it’s a variable used for how Go imports packages. Do some search if you want to know more about this. There are others environment variables that can be set to define how you want go would work.

WORKDIR , COPY , RUN

Next, we move between directories and install dependencies. The comments provided are already self-explaining.

EXPORT , CMD

Lastly, we export port 3000 from inside our container to the outside since the application will listen to this port to work. And we define a default command to execute when we run our image which is CMD [“/dist/main”] .

To build image run following command:

docker build . -t go-dock

We build our image and tagged it with name go-dock . Now we have our image ready, but it just does nothing at the moment. The next thing we want is to run our image so that it will be able to handle our request. A running image is called a container.

To run an image, type following:

docker run -p 3000:3000 go-dock

The flag -p is to define the port binding. Since our app inside the container is running on port 3000 then we bind it to the host port, this time also 3000. If you want to bind to another port then you can run it with -p $HOST_PORT:3000 . for example -p 5000:3000 .

And we specify which image we want to run, this time go-dock .

Test if the server running correctly.

And we get a response.