Image by Pexels from Pixabay

Here’s a tiny tip on how to test your Go application inside a Docker container.

Suppose you’re writing an application in Go, and you want to test how it will behave inside a container. Of course, you could write a Dockerfile for your application, build an image and run it, but that might be too long, especially if you need a fast turnaround while you finetune your Go app to the container environment.

Here’s how to quickly run a throwaway container to test your app. There’s an official golang image based on Alpine, so you can go to your app’s folder and a Go-enabled container as follows:

docker run -v .:/app -w /app -p 8081:8080 -it golang
  • The -v .:/app parameter makes the current directory (with the source code of your app) available as the /app directory inside the container;
  • The -w /app parameter sets the working directory to the same place where your app sources will be available inside the container;
  • The -p 8081:8080 parameter makes the port 8080 from inside the container available on your local port 8081. You’ll need this in case your app listens to some port, and you want to be able to connect to it. Adjust this parameter as needed.
  • -it connects your terminal to the container pseudo-terminal and keeps it open. This allows you to execute commands inside the container.

Now you can simply run your app using go run:

> go run main.go
Hello World!

If you don’t like this golang image for some reason, you can take a regular Alpine image and run it with a similar command:

docker run -v .:/app -w /app -p 8080:8080 -it alpine

But the Alpine distribution doesn’t have Go installed by default, so you’ll need to install it there using the following command:

apk update && apk add --no-cache go 

You’re now ready to run your app inside this container:

> go run main.go
Hello world!

Happy coding!