Get Hyped: Using Docker + Go with MongoDB
Rate this tutorial
In the developer community, ensuring your projects run accurately regardless of the environment can be a pain. Whether it’s trying to recreate a demo from an online tutorial or working on a code review, hearing the words, “Well, it works on my machine…” can be frustrating. Instead of spending hours debugging, we want to introduce you to a platform that will change your developer experience:
Docker is a great tool to learn because it provides developers with the ability for their applications to be used easily between environments, and it's resource-efficient in comparison to virtual machines. This tutorial will gently guide you through how to navigate Docker, along with how to integrate
on the platform. We will be using this project to connect to our previously built MongoDB Atlas Search Cluster made for using
. Stay tuned for a fun read on how to learn all the above while also expanding your Gen-Z slang knowledge from our synonyms cluster. Get hyped!
There are a few requirements that must be met to be successful with this tutorial.
- A M0 or better MongoDB Atlas cluster
- Docker Desktop
Like previously mentioned, you don’t need Go installed and configured on your host computer to be successful. However, it wouldn’t hurt to have it in case you wanted to test things prior to creating a Docker image.
On your computer, create a new project directory, and within that project directory, create a src directory with the following files:
The go.mod file is our dependency management file for Go modules. It could easily be created manually or by using the following command:
The main.go file is where we’ll keep all of our project code.
Starting with the go.mod file, add the following lines:
This brings us into the building of our simple API.
Within the main.go file, add the following code:
There’s more to the code, but before we see the rest, let’s start breaking down what we have above to make sense of it.
You’ll probably notice our
Earlier in the tutorial, we mentioned that this example is heavily influenced by a
that used Twitter data. We highly recommend you take a look at it. This data structure has some of the fields that represent a tweet that we scraped from Twitter. We didn’t map all the fields because it just wasn’t necessary for this example.
Next, you’ll notice the following:
These will be the functions that hold our API endpoint logic. We’re going to skip these for now and focus on understanding the connection and configuration logic.
As of now, most of what we’re interested in is happening in the
The first thing we’re doing is connecting to MongoDB:
You’ll probably notice the
MONGODB_URIenvironment variable in the above code. It’s not a good idea to hard-code the MongoDB connection string in the application. This prevents us from being flexible and it could be a security risk. Instead, we’re using environment variables that we’ll pass in with Docker when we deploy our containers.
You can visit the MongoDB Atlas dashboard for your URI string.
The database we plan to use is
synonymsand we plan to use the
tweetscollection, both of which we talked about in that previous tutorial.
After connecting to MongoDB, we focus on configuring the Gorilla Web Toolkit:
In this code, we are defining which endpoint path should route to which function. The functions are defined, but we haven’t yet added any logic to them. The application itself will be serving on port 12345.
As of now, the application has the necessary basic connection and configuration information. Let’s circle back to each of those endpoint functions.
We’ll start with the
GetTweetsEndpointbecause it will work fine with an M0 cluster:
In the above code, we’re saying that we want to use the
Findoperation on our collection for all documents in that collection, hence the empty filter object.
If there were no errors, we can get all the results from our cursor, load them into a
Tweetslice, and then JSON encode that slice for sending to the client. The client will receive JSON data as a result.
Now we can look at the more interesting endpoint function.
The first important thing in the above code to note is the following:
We’re obtaining the query parameters passed with the HTTP request. We’re expecting a
qparameter to exist with the search query to be used.
To keep things simple, we make use of a single stage for the MongoDB aggregation pipeline:
In this stage, we are doing a text search with a specific index and a specific set of synonyms. The query that we use for our text search comes from the query parameter of our HTTP request.
Assuming that everything went well, we can load all the results from the cursor into a
Tweetslice, JSON encode it, and return it to the client that requested it.
If you have Go installed and configured on your computer, go ahead and try to run this application. Just don’t forget to add the
MONGODB_URIto your environment variables prior.
Let’s get started with Docker! If it’s a platform you’ve never used before, it might seem a bit daunting at first, but let us guide you through it, step by step. We will be showing you how to download Docker and get started with setting up your first Dockerfile to connect to our Gen-Z Synonyms Atlas Cluster.
Once you have that up and running, it’s time to create your very first Dockerfile.
At the root of your project folder, create a new Dockerfile file with the following content:
This format is what many Dockerfiles are composed of, and a lot of it is heavily customizable and can be edited to fit your project's needs.
The first step is to grab a base image that you’re going to use to build your new image. You can think of using Dockerfiles as layers to a cake. There are a multitude of different base images out there, or you can use
FROM scratchto start from an entirely blank image. Since this project is using the programming language Go, we chose to start from the
golangbase image and add the tag
1.16to represent the version of Go that we plan to use. Whenever you include a tag next to your base image, be sure to set it up with a colon in between, just like this:
golang:1.16. To learn more about which tag will benefit your project the best, check out
on the subject.
This site holds a lot of different tags that can be used on a Golang base image. Tags are important because they hold very valuable information about the base image you’re using such as software versions, operating system flavor, etc.
Let’s run through the rest of what will happen in this Dockerfile!
It's optional to include a
MAINTAINERfor your image, but it’s good practice so that people viewing your Dockerfile can know who created it. It's not necessary, but it’s helpful to include your full name and your email address in the file.
WORKDIR /go/src/appcommand is crucial to include in your Dockerfile since
WORKDIRspecifies which working directory you’re in. All the commands after will be run through whichever directory you choose, so be sure to be aware of which directory you’re currently in.
COPY ./src .command allows you to copy whichever files you want from the specified location on the host machine into the Docker image.
Now, we can use the
RUNcommand to set up exactly what we want to happen at image build time before deploying as a container. The first command we have is
RUN go get -d -v, which will download all of the Go dependencies listed in the go.mod file that was copied into the image..
RUN go build -v, which will build our project into an executable binary file.
The last step of this Dockerfile is to use a
CMD [“./docker-golang-example”]. This command will define what is run when the container is deployed rather than when the image is built. Essentially we’re saying that we want the built Go application to be run when the container is deployed.
Once you have this Dockerfile set up, you can build and execute your project using your entire MongoDB URI link:
To build the Docker image and deploy the container, execute the following from the command line:
A Docker Compose file is a nice little step to run all your container files and dependencies through a simple command:
docker compose up.
In order to set up this file, you need to establish a YAML configuration file first. Do this by creating a new file in the root of your project folder, naming it docker-compose, and adding .yml at the end. You can name it something else if you like, but this is the easiest since when running the
docker compose upcommand, you won’t need to specify a file name. Once that is in your project folder, follow the steps below.
This is what your Docker Compose file will look like once you have it all set up:
Let’s run through it!
Next, define which services, otherwise known as containers, you want to be running in your project. We have included
websince we are attaching to our Atlas Search cluster. The name isn’t important and it acts more as an identifier for that particular service. Next, specify that you are building your application, and put in your
portsinformation in the correct spot. For the next step, we can set up our
environmentas our MongoDB URI and we’re done!
Now, run the command
docker compose upand watch the magic happen. Your container should build, then run, and you’ll be able to connect to your port and see all the tweets!
This tutorial has now left you equipped with the knowledge you need to build a Go API with the MongoDB Golang driver, create a Dockerfile, create a Docker Compose file, and connect your newly built container to a MongoDB Atlas Cluster.
Using these new platforms will allow you to take your projects to a whole new level.