how to run python manage.py migrate inside a docker container that runs Django with apache2

Question:

I’m running Django app inside Docker container with apache2, I need to add the command python manage.py migrate inside the Dockerfile or docker-compose but am unable to run it .

Dockerfile

FROM ubuntu

RUN apt-get update

# Avoid tzdata infinite waiting bug
ARG DEBIAN_FRONTEND=noninteractive
ENV TZ=Africa/Cairo

RUN apt-get install -y apt-utils vim curl apache2 apache2-utils
RUN apt-get -y install python3 libapache2-mod-wsgi-py3
RUN ln /usr/bin/python3 /usr/bin/python
RUN apt-get -y install python3-pip
#Add sf to avoid ln: failed to create hard link '/usr/bin/pip': File exists
RUN ln -sf /usr/bin/pip3 /usr/bin/pip
RUN pip install --upgrade pip
RUN pip install django ptvsd
COPY www/demo_app/water_maps/requirements.txt requirements.txt
RUN pip install -r requirements.txt
ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf
EXPOSE 80
WORKDIR /var/www/html/demo_app
CMD ["apache2ctl", "-D", "FOREGROUND"]
CMD ["python", "manage.py", "migrate", "--no-input"]

docker-compose

version: "2"

services:

  db:
    image: postgres
    volumes:
      - ./data/db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=database_innvoentiq
      - POSTGRES_USER=database_user_innvoentiq
      - POSTGRES_PASSWORD=mypasswordhere
      - PGDATA=/tmp
  django-apache2:
    build: .
    container_name: water_maps
    environment:
      - POSTGRES_DB=database_innvoentiq
      - POSTGRES_USER=database_user_innvoentiq
      - POSTGRES_PASSWORD=mypasswordhere
      - PGDATA=/tmp
    ports:
      - '80:80'
    volumes:
      - ./www/:/var/www/html
    depends_on:
      - db

what happens here is that the container exists after running the last CMD in the Dockerfile

Asked By: Ahmed Wagdi

||

Answers:

Do this:

django-apache2:
    build: .
    container_name: water_maps
    environment:
      - POSTGRES_DB=database_innvoentiq
      - POSTGRES_USER=database_user_innvoentiq
      - POSTGRES_PASSWORD=mypasswordhere
      - PGDATA=/tmp
    ports:
      - '80:80'
    volumes:
      - ./www/:/var/www/html
    command: >
       sh -c 'python manage.py migrate &&
              python manage.py runserver 0.0.0.0:8000'
    depends_on:
      - db

or run docker-compose using below command:

docker-compose run --rm projectname sh -c "python manage.py filename"
Answered By: Manoj Tolagekar
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.