How to Containerize Golang app with Docker

How to containerize Golang app using Docker


To containerize a Golang app is similar to any other project. We need to use the base image for golandg and build the app.

Install Docker desktop , if you are on windows and create an account first. Then in the project create Dockerfile ( no extension required) with following command.

Save the file in root of the project

FROM  golang:1.18beta2-bullseye
RUN mkdir /app
ADD . /app
WORKDIR /app
RUN go build -o main .
CMD ["/app/main"]

Building the Docker Image

Go to the terminal and CD into the project folder and build the image. Docker image can be used to run different process.

docker build -t my-go-app . 

try to list image using docker images command.

Using the image

To use the image we created withrun command.

docker run -d -p 8080:8080 --name test1 my-go-app

The above command will run the image in detached mode, leaving console reedy for another execution.

It also exposed to port internal 8080:8080. Go to the browser and try localhost:8080 and it should have working.

Stopping, Starting and removing containers

Using docker stop <container-name/id>. Once it stopped can delete using docker rm container-name/id command.

Need to start again ? use the docker start command.

Wanna know running processes/ containers ? Try docker ps.

Howto to remove all containers at once in docker

How to remove all containers in docker


Docker is a developer tool which help us to run applications in an isolated environment, where you can start a service, app,local host, MySQL, SQL server, mongodb etc.

Get the container id

To remove container we can use rm command with ids of container. First thing we need grab all the ids using the

docker pa -aq

Then use those ids as arguments to stop command as follows

docker rm $(docker ps -aq)

that’s it

Docker posts that may help you