Using Docker for your Elixir Phoenix application
Jamie Neubert Pedersen
Posted on December 10, 2021
A nifty way to setup an Elixir development environment is to use Docker instead of using asdf
or installing the Elixir toolchain locally.
Docker has the option to mount a directory into the container which we can exploit to mount whatever folder we are currently in by using the unix command pwd
(print working directory).
We can also instruct Docker to expose a port and remove the container once it is stopped. Putting these things together we can get a Elixir environment entirely contained in Docker. The base of the command would be this in bash:
docker run --mount type=bind,source=$(pwd),target=/app -p 4000:4000 --rm elixir:latest
From this point we can extend it to do whatever we want with Elixir, such as running mix
commands.
Although we have to create a Docker image that has these tools contained. Here is an example of a Docker image that you can build with docker build -t elixir-env .
in the directory of the Dockerfile:
# Extend from the official Elixir image
FROM elixir:latest
RUN mix local.hex --force \
&& mix archive.install --force hex phx_new \
&& apt-get update \
&& curl -sL https://deb.nodesource.com/setup_lts.x | bash \
&& apt-get install -y apt-utils \
&& apt-get install -y nodejs \
&& apt-get install -y build-essential \
&& apt-get install -y inotify-tools \
&& mix local.rebar --force
ENV APP_HOME /app
RUN mkdir -p $APP_HOME
WORKDIR $APP_HOME
EXPOSE 4000
CMD ["mix", "phx.server"]
After creating the image and tagging it with elixir-env
we can create a Phoenix application by running that container in bash:
docker run --mount type=bind,source=$(pwd),target=/app -p 4000:4000 --rm elixir-env:latest mix phx.server
But where this becomes really interesting is when you alias it to a function in your shell.
Doing that will give you the base CLI tool and make it just as accessible as having it installed locally.
To alias the function you simply do:
alias mix="docker run --mount type=bind,source=$(pwd),target=/app -p 4000:4000 --rm elixir:latest mix"
From here we can simply use mix
to run any further invocations of that container. Thus we can replace it with the local installation and be oblivious to it running through Docker.
This technique is quite powerful for testing out environments or if you can't get a specific program to run locally on your machine because of conflicting dependencies. Creating a program running in Docker saves you from dealing with global dependencies and allows you the flexibility of a clean installation.
Posted on December 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.