Error: Postgres database import in docker container
Set up a database dump mount
You'll need to mount the dump into the container so you can access it. Something like this in docker-compose.yml:
db: volumes: - './db_dump:/db_dump'
Make a local directory named db_dump
and place your db_dump.gz
file there.
Start the database container
Use POSTGRES_DB
in the environment (as you mentioned in your question) to automatically create the database. Start db
by itself, without the rails server.
docker-compose up -d db
Import data
Wait a few seconds for the database to be available. Then, import your data.
docker-compose exec db gunzip /db_dump/db_dump.gzdocker-compose exec db psql -U postgres -d dbname -f /db_dump/db_dump.gzdocker-compose exec db rm -f /db_dump/db_dump.gz
You can also just make a script to do this import, stick that in your image, and then use a single docker-compose command to call that. Or you can have your entrypoint script check whether a dump file is present, and if so, unzip it and import it... whatever you need to do.
Start the rails server
docker-compose up -d web
Automating this
If you are doing this by hand for prep of a new setup, then you're done. If you need to automate this into a toolchain, you can do some of this stuff in a script. Just start the containers separately, doing the db import in between, and use sleep
to cover any startup delays.
web_1 exited with code 0
Did you tried check the log of web_1
container? docker-compose logs web
I strongly recommend you don't initialize your db container manually, make it automatically within the process of start container.
Look into the entrypoint of postgres, we could just put the db_dump.gz
into /docker-entrypoint-initdb.d/
directory of the container, and it will be automatic execute, so docker-compose.yml
could be:
db: volumes: - './initdb.d:/docker-entrypoint-initdb.d'
And put your db_dump.gz
into ./initdb.d
on your local machine.
When you use commanddocker-compose run -d db
you run a separate container it means you are running 3 containers where 1 is application 2 are dbs. The container you run using above command will not be a part of service. compose is using separate db.
So instead of running docker-compose up -d db
run docker-compose up -d
and continue with your script