How to migrate to dockerfile if the database is in

2019-08-25 09:14发布

问题:

Such situation: There is a container with a dB and Django container of the application which through-link connects to a dB and starts itself:

FROM deb_base
COPY vfnd vfnd
CMD ["python", "./vfnd/manage.py", "runserver", "0.0.0.0:8001"]

The bad thing is that you have to run python vfnd/manage.py migrate manually every time I launch the containers.

Tried the following code:

FROM deb_base
COPY vfnd vfnd
RUN ["python", "./vfnd/manage.py", "migrate"]
CMD ["python", "./vfnd/manage.py", "runserver", "0.0.0.0:8001"]

However, when you try to build the image, you receive an error on this command

Step 3/4 : RUN ["python","./vfnd/manage.py","migrate"]
 ---> Running in 5791de6fc147
Traceback (most recent call last):
  File "/usr/share/Python-3.7.3/lib/python3.7/site-packages/django/db/backends/b
ase/base.py", line 216, in ensure_connection
    self.connect()
  File "/usr/share/Python-3.7.3/lib/python3.7/site-packages/django/db/backends/b
ase/base.py", line 194, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/usr/share/Python-3.7.3/lib/python3.7/site-packages/django/db/backends/p
ostgresql/base.py", line 168, in get_new_connection
    connection = Database.connect(**conn_params)
  File "/usr/share/Python-3.7.3/lib/python3.7/site-packages/psycopg2/__init__.py
", line 126, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not translate host name "pg_1" to address: Name
 or service not known

How can I implement my idea

回答1:

Put those commands in a script and run it as entrypoint in dockerfile.

  • Create init.sh script with contents
#!/bin/bash

python /vfnd/manage.py migrate
python /vfnd/manage.py runserver 0.0.0.0:8001

exec "$@"
  • Change your dockerfile to
FROM deb_base
COPY vfnd /
COPY init.sh /init.sh
ENTRYPOINT ["/init.sh"]

Hope this helps.



标签: django docker