Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Docker Tip #62: Using 2 Dockerfiles in the Same Compose Project

blog/cards/docker-tips-and-tricks.jpg

This use case comes up often if you work on a project where you need a separate Dockerfile for your back-end and front-end.

A prime example would be let’s say you had your back-end written in Python, Node, Ruby, Elixir or any language you prefer.

But then to deal with your front-end assets you are using Webpack (or similar).

It’s a reasonable idea to keep both of these as separate Docker images. Especially since Webpack in development will likely involve setting up a watcher service so you don’t need to keep re-building your assets on every change.

That means we have 2 separate processes, so running 2 containers is a good idea.

A Docker Compose snippet of using (2) Dockerfiles for (2) different services:
services:
  webpack:
    build:
      context: "."
      dockerfile: "Dockerfile.webpack"

  web:
    build: "."

In the web case it just uses our Dockerfile in the root of the directory but then in the webpack case it looks for Dockerfile.webpack instead.

A fully working example can be found in the Docker best practices example repo that has a few web framework examples.

A variant of this set up would be to set the context to ./assets and put a Dockerfile in there instead of using a different Dockerfile filename but personally I like it when all of my Docker related files are in the same directory.

Free Intro to Docker Email Course

Over 5 days you'll get 1 email per day that includes video and text from the premium Dive Into Docker course. By the end of the 5 days you'll have hands on experience using Docker to serve a website.



Comments