docker-compose - database migrations and other pre

2019-05-01 11:45发布

问题:

I have a sample django app that I am trying to get up and running using docker.

docker-compose up brings up the web, db and other containers along with links between them. But there are pre and post scripts that might need to be run..

example of pre-scripts in my scenario:

git
pip
docker
docker-compose
wget

example of post-scripts :

Database migrations, usually done manually using docker run web... after the containers are up and running.

Currently I have a deploy.sh at the root of app which follows logic like this..(I choose a ubuntu image when launching)

#assuming I always choose ubuntu base image
sudo apt-get install x
sudo apt-get install y
sudo apt-get install z
docker-compose build .; docker-compose up -d;
docker-compose run web "python manage.py makemigrations"

My questions:

1) what is the best way to run these commands?

2) Are database migrations run each time you deploy (from scratch?) - or is this issue taken care of by volumes?

回答1:

You have two options:

  1. You can run these commands in the dockerfile for your images; as each dockerfile is run when compose is running - your images will have the results of these commands. This is particularly useful when you are doing os-level upgrades and configuration bootstrapping (like your apt-get commands).

  2. For runtime-level configuration (things you need to do once the system is up), use the command directive in your docker-compose.yml file. These would be your migrations (if you need to run them each time).

If you want to persist your data across runs of docker compose (that is, your data should remain when you restart the container); then you need either persistent mapping against your host or a data volume that's shared - which you can configure in your docker-compose.yml as well.

docker-compose will happily run whatever script you provide - it doesn't know if it needs to run it, its just executing commands. It is up to you to make sure your pre, post, bootstrap scripts are intelligent enough that they can be repeated even if their effective results are already applied.