Running containers with docker-compose

As promised in the previous post here, today we will go over running containers with docker-compose. We will use the same source code(react covid dashboard) as in the last post. So, if you want to follow along you can use the same.

Below is the docker-compose.yml file from the repo.

---
version:  "3.7"

services:
  covid-app:
    tty:  true
    image:  node:12-alpine
    command:  sh -c "rm -rf node_module && rm -f yarn.lock && npm install [email protected] && npm install && npm start"
    ports:
      - 80:3000
    working_dir:  /app
    volumes:
      - ./:/app

Unfortunately, I couldn’t get this to run with yarn as yet. Running the simple Dockerfile in the previous case was challenging because there were errors that didn’t show up when run locally or on Heroku. While we’re at it, if you need to know how to run this dashboard locally or in Heroku, then check this post. So, as I was saying, Dockerfile was challenging but I managed to get it to work with yarn(and vanilla node). But on this case, it was taking too long to find a fix for yarn. Since my main goal is to demonstrate on how docker-compose works, I just made sure it works with vanilla node.

Why docker-compose?

So let’s just cut to the chase. If it works in Dockerfile, then why bother? The answer to that is, 4 things.

  1. You can run multiple containers and is good for starting multi-container environments.
  2. The application run using the containers, can be started using a single command.
  3. You can leverage the Dockerfile to build the images. (Not covered here.)
  4. Can make instant live changes to the containers.

Now let’s go in to the details of the above 3 points. Regarding the first point, under the services section in the YAML file, we only see one container named covid-app. But there can be more as required. In our case we only have one. About the second point we can start all the containers using a single command. The command is docker-compose up -d . This command will build and run the containers. Here, in case we need to maintain a sequence as to what container needs to be up first before another one could start, we can use the depends_on section to do so. About the 3rd point, we can simply add a build section to the above YAML to re-purpose the Dockerfile and build based on that.

You might have noticed that we are using volumes in docker-compose. (Which we didn’t use in Dockerfile as we just copied over the contents to the contianer.) That is one key difference between docker-compose and Dockerfile. Since we have a volume and our application code which is available locally( on our hosts’ hard drive) has been mounted in to the container as a volume, the changes we make on the code locally, results in changes in the containers instantly. This can be an advantage and a disadvantage as well.

That’s all for this post. Catch you all next time with another post 🙂