Django Manage.py Migrate from Google Managed VM Dockerfile - How?

402 views Asked by At

I'm working on a simple implementation of Django hosted on Google's Managed VM service, backed by Google Cloud SQL. I'm able to deploy my application just fine, but when I try to issue some Django manage.py commands within the Dockerfile, I get errors.

Here's my Dockerfile:

FROM gcr.io/google_appengine/python

RUN virtualenv /venv -p python3.4

ENV VIRTUAL_ENV /venv
ENV PATH /venv/bin:$PATH

# Install dependencies.
ADD requirements.txt /app/requirements.txt
RUN pip install -r /app/requirements.txt

# Add application code.
ADD . /app

# Overwrite the settings file with the PROD variant.
ADD my_app/settings_prod.py /app/my_app/settings.py

WORKDIR /app

RUN python manage.py migrate --noinput

# Use Gunicorn to serve the application.
CMD gunicorn --pythonpath ./my_app  -b :$PORT --env DJANGO_SETTINGS_MODULE=my_app.settings my_app.wsgi
# [END docker]

Pretty basic. If I exclude the RUN python manage.py migrate --noinput line, and deploy using the GCloud tool, everything works fine. If I then log onto the VM, I can issue the manage.py migrate command without issue.

However, in the interest of simplifying deployment, I'd really like to be able to issue Django manage.py commands from the Dockerfile. At present, I get the following error if the manage.py statement is included:

django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/cloudsql/my_app:us-central1:my_app_prod_00' (2)")

Seems like a simple enough error, but it has me stumped, because the connection is certainly valid. As I said, if I deploy without issuing the manage.py command, everything works fine. Django can connect to the database, and I can issue the command manually on the VM.

I wondering if the reason for my problem is that the sql proxy (cloudsql/) doesn't exist when the Dockerfile is being deployed. If so, how do I get around this?

I'm new to Docker (this being my first attempt) and newish to Django, so I'm unsure of what the correct approach is for handling a deployment of this nature. Should I instead be positioning this command elsewhere?

1

There are 1 answers

1
Vadim On BEST ANSWER

There are two steps involved in deploying the application.

In the first step, the Dockerfile is used to build the image, which can happen on your machine or on another machine.

In the second step, the created docker image is executed on the Managed VM.

The RUN instruction is executed when the image is being built, not when it's being run.

You should move manage.py to the CMD command, which is run when the image is being run.

CMD python manage.py migrate --noinput && gunicorn --pythonpath ./my_app  -b :$PORT --env DJANGO_SETTINGS_MODULE=my_app.settings my_app.wsgi