If you are not a Docker expert, like most people, the best possible way to learn is to start up a terminal and mess around in an empty container. One example is to open up an Ubuntu image, install python, and write the iconic “Hello World” script. Doing this all within the Ubuntu image, Docker will start to make sense.
This is the fun way to learn Docker: Start from a base image and from within, install all necessary dependencies to get your program to work.
Say you have a simple Golang application that imports other Go files. As expected, we will always import Go files via the import statement with respect to our set GOPATH:
With the database package imported, we can easily import exportable functions. Here, I will define a route to add orders to the database(Postgres):
With this basic application created, its time to place it into a Dockerfile, so we can easily ensure that anyone that clones my repo can run the server without dependency errors.
The quick: a Golang Dockerfile differs from other languages because placing all code in an arbitrary directory will not allow your app to correctly import other Go packages. To fix this issue, we must place all of our code in the newly created GOPATH —
The way that I figured this out was by playing with an empty Golang container. The Docker command is —
docker run -dit — name dev golang
The flag -d allows the container to run in the background, -it is so that there is an interactive terminal always up because if these flags were not called, the empty container will just stop. We named this new container dev, also. To actively play within this container we need the command —
docker exec -it dev bash
This allows us to enter the container and work within its file system. Again, -it beings out the terminal.
I was able to solve my issued of my files not being able to locate other file by running the command ‘echo $GOPATH’ that returned the simple ‘/go’. Although this was an obvious fact from go applications, this problem stumped me for weeks. I mistakenly imported all of my files outside of the GOPATH, so my files were not able to be found and compiled.
From within the container, its pretty easy to use the linux’s package manager (yum, apt-get, etc.) to install needed packages. Once you are able to run your program within this sandbox container, the last task is to just recount all of your steps into a Dockerfile. Although this Dockerfile was not made with efficiency in mind, it serves as the base script to get your program off the ground and leaves room to make efficient changes that can drastically reduce the size of the image.