Requirements:
To follow along with this tutorial, ensure that you have the following tools and resources:
- Docker Engine version 23 and above
- Installed Ruby interpreter on the host machine
- Network connectivity to download the Docker images
- Sufficient permissions to run and use Docker on the host machine
With the given requirements met, let us proceed with the tutorial.
Create a Ruby App
The first step is setting up the Ruby application that we wish to containerize. For simplicity, we build a basic HTTP server using Ruby which returns a basic “Hello world”.
Create the directory to the store the code and navigate into the directory:
cd hello_http
In the project directory, create a file to store the source code. You can name this file with any appropriate name.
Next, edit the “main.rb” file and store the source code for your application. In our case, the example code is as follows:
server = WEBrick::HTTPServer.new(Port: 2030)
server.mount_proc '/' do |req, res|
res.content_type = 'text/plain'
res.body = 'Hello World from Docker'
end
trap('INT') { server.shutdown }
server.start
The given example code uses the webrick library which is included in the Ruby ecosystem by default to create a basic HTTP server that runs on port 2030.
Setup the Dockerfile
Once we have the application ready and configured, we can proceed and setup the Dockerfile. This defines all the instructions on how we wish the container to run.
Create a Dockerfile in the project directory:
Next, edit the file and add the build instructions as follows:
WORKDIR /app
COPY main.rb .
EXPOSE 2030
CMD ["ruby", "main.rb"]
In this case, we use the Dockerfile to specify that we wish to use the Ruby image version 3.3.0 and set the working directory to “/app”. We then copy the “main.rb” script to the working directory.
We also expose port 2030 to allow us to access the HTTP server. To ensure that the server starts when the container is run, we use the CMD instruction and pass the “main.rb” file.
Build the Docker Image
We can now proceed and build the image from the Dockerfile. We can use the “docker build” command as follows:
This command tells Docker to build an image named “ruby-http-server” using the current directory as the build context.
Run the Docker Container
Once we successfully built the image, we can create a container from the image as shown in the following command:
The previous command should create a new container using the previously created image and map port 2030 on the container to port 2030 on the host machine.
To test whether the web server is working, we can make an HTTP request to the container address as follows:
This should print the message that is defined in the “main.rb” file.
Conclusion
In this post, we covered the fundamentals of containerizing a Ruby application using the Dockerfile and the official Ruby image.