Go
In this guide we will setup a Dockerfile for your Go Application.
Prerequisites
To follow this tutorial, you will need the following:
- Go
- [Docker] to build standalone containers to serve your Go app.
This guide assumes that you have basic knowledge of the above-mentioned technologies and tools. If you are not familiar with any of them, it is recommended to review their official documentation and tutorials to get up to speed before proceeding with this guide.
Go Http Server
- Run the command
go mod init go-http-server
to set up your project and manage its dependencies. - Now, create a file named
main.go
and add the following code to set up a basic http server using the gin web framework.
- Export the required environment variables,
- Run
go mod download
command to download the required dependencies. - Run the command
go run main.go
to start the server.
Dockerize
Dockerizing makes your app run anywhere, agnostic of the platform.
Create .dockerignore
Before creating the dockerfile, let’s create a .dockerignore
file and add that contents that should not be copied over
to the docker file system.
Read more about .dockerignore here
Creating a .dockerinogre
file and adding folders like node_modules
is must, since dependencies will be installed
while building the image based on the platform preferences used. Copying those from file system will overwrite the
installed dependecies and might error out during deployments
Create Dockerfile
Now, Create a Dockerfile. The Dockerfile is a text file that contains the instructions for Docker to build the image.
The Dockerfile is posted for reference with steps to create the production image. Though docker supports
Multi-Stage Builds we won’t be using that here. In this example
we will copy source code
and build and run it inside the container. You can opt for multi stage build, if you want to
build the go binary in build stage and run it in another stage.
Refer to this doc to know more about building docker images for go applications.
Build and test docker image
Now you can build and run the Docker image. To build the Docker image:
This command builds the go-http-server
image for platform linux/amd64
.
If you are locally testing your application, you can skip the platform
key to build the images
Run the docker image
Let’s run the Docker container using the image created of the react application with the command below.
Done 🎉
You can now commit and push the Dockerfile to your git repo. Create a service now to point at the git repository and branch name to deploy this image.