Use Docker to Serve a Static Ruby Site Locally
2017-02-11Here I am nearly three years after my first post about Creating a Ruby Static Blog and starting from scratch again.
I am using AWS S3 to host my site, but I wanted a simple server running locally to develop against.
Docker proved perfect for this.
Summary
Dockerfile
FROM ruby:2.3.3
ENV APP_HOME /app
RUN mkdir $APP_HOME
WORKDIR $APP_HOME
COPY Gemfile* $APP_HOME/
RUN bundle install
ADD . $APP_HOME
RUN ruby build.rb
CMD ruby -run -e httpd ./_site -p 3000
status.ru
root=Dir.pwd + "/_site"
run Rack::Directory.new("#{root}")
docker build -t blog .
docker run -d -p 8080:3000 --rm blog
Breaking it down
The Dockerfile
FROM ruby:2.3.3
Start with ruby version 2.3.3
ENV APP_HOME /app
Set an environment variable $APP_HOME
to /app
RUN mkdir $APP_HOME
Create the /app
directory inside the container
WORKDIR $APP_HOME
Change the working directory to /app
COPY Gemfile* $APP_HOME/
Bring your Gemfile and Gemfile.lock into the container
RUN bundle install
Install your gems
ADD . $APP_HOME
Copy your host app directory into the container
At this point you might be wondering why we copied the Gemfile in above when we are just copying it back in again right here.
We want to do that so that we don't have to reinstall our gems every time we want to load an update of our app (which creates a new container layer).
RUN ruby build.rb
Execute the build.rb
script inside the container
CMD ruby -run -e httpd ./_site -p 3000
Run a simple Webrick
server inside the container. Serve the ./_site
directory on port 3000
The webserver
status.ru
This is the config file the webrick server is going to use
root=Dir.pwd + "/_site"
run Rack::Directory.new("#{root}")
Inside status.ru
and tells the server where to look
Run it
docker build -t blog .
Build the contents of the Dockerfile
in an image tagged blog
docker run --name site -d -p 8080:3000 --rm blog
Run a container as a background process -d
and forward requests from port
8080
on the host to port 3000
on the container. Remove the container when I
exit --rm
and use the image blog
and name the container site
so that it is
easy to stop.
http://localhost:8080
and you should see your site.
Commands to know
Verify the blog image is now stored locally
docker images
Verify that site
is up and running
docker ps -a
Your content should be available in your browser
localhost:8080 OR 127.0.0.1:8080
Stop the container
docker stop site
Start the container
docker start site
Destroy the container
docker stop site && docker rm site
Remove the blog image
docker rmi blog