如果数据库位于另一个容器中,如何迁移到dockerfile?

时间:2019-07-03 15:06:24

标签: django docker

这种情况: 有一个带有dB的容器和该应用程序的Django容器,它通过链接连接到dB并自行启动:

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

不好的是,每次我启动容器时,都必须手动运行python vfnd / manage.py迁移。

尝试以下代码:

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

但是,当您尝试构建映像时,此命令会收到错误消息

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

我如何实现我的想法

1 个答案:

答案 0 :(得分:0)

将这些命令放在脚本中,然后将其作为入口点在dockerfile中运行。

  • 使用内容创建init.sh脚本
#!/bin/bash

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

exec "$@"
  • 将您的dockerfile更改为
FROM deb_base
COPY vfnd /
COPY init.sh /init.sh
ENTRYPOINT ["/init.sh"]

希望这会有所帮助。