简体   繁体   中英

What is the best way to volume existing database to the container?

Need to run project via docker containers. I need to mount existing database to postgres container. Have the next in my docker-compose.yml


services:

  web:
    build: .
    env_file: .env
    command: bash -c "python manage.py collectstatic --no-input && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000"
    ports:
      - "8000:8000"
    depends_on:
      - redis
      - postgres
    restart: always
    volumes:
      - static:/static
    expose:
      - 8000
    environment:
      - .env
    links:
      - postgres
      - redis

  redis:
    image: "redis:alpine"


  postgres:
    image: "postgres:10"
    env_file:
      - .env
    volumes:
      - POSTGRES_DATA:/var/lib/postgresql/data
    ports:
      - "5433:5432"
    expose:
      - 5433

volumes:
    POSTGRES_DATA:
    static:

From my.env file

POSTGRES_NAME=dbname
POSTGRES_USER=dbuser
POSTGRES_PASSWORD=dbpassword
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_DATA=/var/lib/postgresql/10/main

But inside my web container I have next logs

  File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 130, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: FATAL:  database "dbname" does not exist

It means that databse mount failed. But I really can not find reason why it happens.

I'm not sure, but you can try this command: docker-compose down -v to remove the volumes along with the containers

from the docs :

Warning: scripts in /docker-entrypoint-initdb.d are only run if you start the container with a data directory that is empty; any pre-existing database will be left untouched on container startup. One common problem is that if one of your /docker-entrypoint-initdb.d scripts fails (which will cause the entrypoint script to exit) and your orchestrator restarts the container with the already initialized data directory, it will not continue on with your scripts

so you need to provide the data:

volumes:
  - /path/where/my/data/are:/var/lib/postgresql/data

I can see in your compose that you use the volume POSTGRES_DATA which I think is a new empty named Volume

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM