Dockerize Phoenix Applications
I assume you have created a Phoenix application. To be fair, most of the contents of this post is taken from this awesome blog post. This is not meant to be a ripoff, just wanted to document this process for myself.
I had some problems with Brunch (probably related to a problem I had with sass-brunch), so I replaced Brunch with Webpack instead. I encourage you to do the same, webpack seems to be the current standard anyways. The Dockerfile in this blog post “require” you to use webpack. You can follow this blog post to replace Brunch with Webpack, then come back here and follow the rest of the tutorial. No worries, it is very easy. However, if you still want to use Brunch, just edit the Dockerfile (look at the comments).
Creating a Dockerfile
Well, lets begin by creating a
Dockerfile that will contain instructions for building a docker image of your Phoenix application.
# Because it contains Elixir per default FROM trenpixster/elixir:1.3.0 # Install NodeJS, to build frontend stuff RUN curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - && apt-get install -y nodejs RUN mkdir /app WORKDIR /app # Install Elixir Dependencies ADD mix.* ./ RUN MIX_ENV=prod mix local.rebar RUN MIX_ENV=prod mix local.hex --force RUN MIX_ENV=prod mix deps.get # Install Node Dependencies ADD package.json ./ RUN npm install # Compile Phoenix application ADD . . RUN MIX_ENV=prod mix compile # Compile assets (Here we use a npm script that runs webpack instead of Brunch) # Use this line instead of the one after, if you want to use brunch # RUN NODE_ENV=production node_modules/brunch/bin/brunch build --production RUN NODE_ENV=production npm run deploy RUN MIX_ENV=prod mix phoenix.digest # Exposes this port from the docker container to the host machine EXPOSE 4000 # The command to run when this image starts up CMD MIX_ENV=prod mix phoenix.server
To avoid bloating your docker image, add a
.dockerignore file to ignore some files.
/deps /_build /node_modules /priv/static/* .git .gitignore
Build your image
Issue the following command to create a docker image of your application. You can choose another tag if you want.
$ docker build -t my_phoenix_app .
Start a docker container based on your docker image.
When starting the container, we need to provide an enviroment variable called
PORT that tells the Phoenix application which port to use when starting.
We also use the
--rm switch to remove any existing container runnig with the same name.
$ docker run -p 4000:4000 -e "PORT=4000" --rm --name my_phoenix_app_instance -i -t my_phoenix_app
Open your browser to http://localhost:4000 to view your application. This pretty much wraps it up for this tutorial. Hope you find it useful.