Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
3 views
in DevOps and Agile by (2.3k points)

Is it possible to write a docker-compose.yml file like given below and use multiple commands?

db:
  image: postgres
web:
  build: .
  command: python manage.py migrate
  command: python manage.py runserver 0.0.0.0:8000
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  links:
    - db

1 Answer

0 votes
by (6.9k points)

You can do this in a few ways you can do this:

Use bash -c:

Eg.
command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
OR
command: >
    bash -c "python manage.py migrate
    && python manage.py runserver 0.0.0.0:8000"

OR

command: bash -c "
    python manage.py migrate
    && python manage.py runserver 0.0.0.0:8000
  "

But be sure to check if the image you are using this command with actually has bash intalled inside of it. A few images don't come with bash installed in them and with a few images you need to put the exact path for bash to work, like so: /bin/bash

Use sh -c:
If bash is not installed on the image you want to work with , you can use sh -c, here is an example on how you can do so:

version: '3'

services:
  app:
    build:
      context: .
    command: >
      sh -c "python manage.py wait_for_db &&
             python manage.py migrate &&
             python manage.py runserver 0.0.0.0:8000"

Use ephemeral containers:

In this third way you simply write the commands in two separate containers, like given below:

db:
  image: postgres
web:
  image: app
  command: python manage.py runserver 0.0.0.0:8000
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  links:
    - db
  depends_on:
    - migration
migration:
  build: .
  image: app
  command: python manage.py migrate
  volumes:
    - .:/code
  links:
    - db
  depends_on:
    - db

It makes things clean and organised, but it would be tedious to do this with multiple commands and there are some logical issues with the use of depends_on.

Hope this helped :)


Get registered in docker training course online and learn how to use docker to its full potential.

Browse Categories

...