I had this quite trivial problem: the version of Go I installed on my pc was quite old.
I started learning Go in February 2020 because the CTO of a client firm was thinking of using it to rebuild the app with a language other than PHP. He changed his mind after understanding Go has pointers.
Months later, though, I picked it up again… only to find out that my Go was a couple of versions behind.
Luckily I also started using Docker, in the meantime, so I don’t actually need to install anything unless I really, really need to.
So how to run Go without installing Go?
Let’s create a main.go
file:
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
}
To run this file:
docker run --rm -v $PWD:/app golang sh -c "go run /app/main.go"
What’s going on here?
--rm
option removes the container after we use it;-v
creates a volume from the current directory to /app;golang
will pull the latest golang image from Docker Hub;sh
runs the shell;- with the
-c
option,sh
will run the command in the following string"go run /app/main.go"
.
The result:
$ docker run --rm -v $PWD:/app golang sh -c "go run /app/main.go"
Hello World!
What about docker-compose?
Let’s say we have a docker-compose.yml
because we are developing some cool app:
version: '3'
services:
app:
image: golang
In a similar fashion as before…:
$ docker-compose run --rm -v $PWD:/app app sh -c "go run /app/main.go"
Creating go-demo_app_run … done
Hello World!
We can of course specify a volume inside the YAML:
version: '3'
services:
app:
image: golang
volumes:
- .:/app
and get rid of the -v option:
$ docker-compose run --rm app sh -c "go run /app/main.go"
Creating go-demo_app_run … done
Hello World!
One last note
Why the beer as featured image? In a previous version of this article I explained that the CTO decided not to go with Go while we were at a brewery. I later decided that I don’t like when people add too much useless personal info on top of their post, removed the explanation, but kept the beer…
1 comment
Comments are closed.