I\'m running a ruby on rails application in docker container. I want to create and then restore the database dump in postgres container. But I\'m
Below is what I\'ve do
When you use command
docker-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
I got it working by adding a container_name
for db container. My db
container have different name (app_name_db_1
) and I was connecting to a container named db
.
After giving the hard-coded container_name
(db
), it gets working.
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.
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.
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
Wait a few seconds for the database to be available. Then, import your data.
docker-compose exec db gunzip /db_dump/db_dump.gz
docker-compose exec db psql -U postgres -d dbname -f /db_dump/db_dump.gz
docker-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.
docker-compose up -d web
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.