Prerequisites
- To successfully follow this guide you will first need to install Docker on your local machine.
- You will also need a Docker Hub account, which includes 1 free private repository.
Notes
- We will be using Docker Hub throughout this learn guide, but GitLab (including the self-hosted version) comes with a built-in container registry for unlimited repositories and is a great alternative.
Create a Docker Image
Create a Dockerfile
in the root of your project.
# We're currently using Ruby 2.5.1
FROM ruby:2.5.1-alpine
# Always nice to know who to contact
LABEL maintainer="niall@absolutedevops.io"
# In a single step - install the dependences (apk is Alpine Linux's
# equivalent to apt) and then remove the cached files (to keep the image
# as small as we can)
RUN apk add --update bash build-base nodejs mariadb-dev tzdata && \
rm -rf /var/cache/apk/*
# Make a directory to hold our app and set the working directory to it
RUN mkdir /app
WORKDIR /app
# Do the gem installation stuff first, in a separate step, because they
# Don't change as often as the code (so we can cache them in a separate
# Docker image layer)
COPY Gemfile Gemfile.lock ./
RUN bundle install --binstubs
# Now copy the current folder to the WORKDIR and drop root privileges
COPY . .
RUN chown -R nobody:nogroup /app
# Compile all assets
RUN bundle exec rake assets:precompile
# Inform Docker what port our container listens on at runtime
EXPOSE 3000
# Set a default command to start the Rails server (can override this for workers, etc.)
CMD ["bundle", "exec", "rails", "server", "-p", "3000"]
Build the Docker image and tag it <your_username>/<repo_name>:<tag>
.
docker build -t <your_username>/k8s-sample-app:v0.1 .
Once this completes you can list all images using the docker images
command:
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
<your_username>/k8s-sample-app v0.1 104edfbbe440 2 minutes ago 617MB
Push to Docker Hub
To create a remote private repository, sign into Docker Hub, click on Repositories then Create Repository.
Log in via your local command line (to allow you to push):
docker login
# enter Docker Hub username and press enter
# enter Docker Hub password and press enter
Push the image to Docker Hub:
docker push <your_username>/k8s-sample-app:v0.1
Releasing a new version
After you've made some changes to your Rails app you will need to rebuild the image (ideally with a new tag) and then push it to Docker Hub.
docker build -t <your_username>/k8s-sample-app:v0.2 .
docker push <your_username>/k8s-sample-app:v0.2