Installing Go In Docker

Installing Go In Docker

Setup Go Development Environment Inside Containers

Installation steps

Step 1: cd into the folder where you want to run the docker container

Step 2: Create a file named "dockerfile" and add the following contents:

FROM golang:1.15-alpine as dev  // "dev" is a developer container

WORKDIR /work // All the work to be done inside the working directory

# FROM golang:1.15-alpine as build   // Later we can create build and run containers for building and running images respectively

# WORKDIR /app COPY ./app/* /app/ RUN go build -o app

# FROM alpine as runtime COPY --from=build /app/app / CMD ./app

Step 3: Run the following command to create a go environment inside the Docker file
docker build --target dev . -t go

docker build command uses the --target flag and this flag targets dev, dot(.) representing we are already present in that directory, -t used for tagging the image, for example, we can choose any tag(here go).

If you are on Linux, you must enable the docker daemon first.

For systemd users- Run systemctl start docker

Try running docker build --target dev . -t go again.

Voila!!! Container image built successfully that is using our development environment.

Step 4: To run the image docker run -it -v ${PWD}:/work go sh

docker run is a command used for running the docker container, -it flag is used for interactive terminal so that we can work inside of a container, -v is for volume mount which is used to mount the present working directory to the folder :/work that indicates the working container that we tagged earlier i.e., go . At last, we specify the entry point which is a shell terminal sh

We are now inside the container where we have a shell environment. ls lists the directories where you can see the dockerfile that you previously created.

Let us check the go version by entering go version

Results

In my terminal, I am running a container with Golang installed. I can see my code via docker volume mount and I can see go as if it was installed on my machine.