Can't run rake db:create in Dockerfile with docker-compose Can't run rake db:create in Dockerfile with docker-compose docker docker

Can't run rake db:create in Dockerfile with docker-compose


When your web image is built (following the instructions of the Dockerfile), it doesn't have a connection to a db container.

The webserver and database images are independents and the containers are linked when you launch them (following the definitions of the docker-compose.yml file).

You cannot link to a container during the image build because it would break the principle that an image build must be reproducible. Similarly, you cannot mount a volume from the host machine during an image build neither.

The docker-compose run web rake db:create command you used is a correct way to initalize the database.

Alternatively, you could launch the containers normaly with docker-compose, and then use the docker exec command to execute rake db:create in the web container.


Below is the correct order

❯ docker-compose run web rake db:createStarting devops-hello-world_db_1 ... doneCreating devops-hello-world_web_run ... doneCreated database 'myapp_development'Created database 'myapp_test'❯ docker-compose updevops-hello-world_db_1 is up-to-dateStarting devops-hello-world_web_1 ... done...


You may want to mount /tmp/db into your postgres container's /var/lib/postgresql/data.

By that the DB will be synced to your host and the next time you restart/rebuild the app this DB will automatically be initialized. Doings so have to run docker-compose run web rake db:create only once when you setup the project like you would to natively and from then on continue with just docker-compose run web rake db:create etc.

version: '3'services:  db:    image: postgres    volumes:      - ./tmp/db:/var/lib/postgresql/data # Here you go!  web:    build: .    command: bundle exec rails s -p 3000 -b '0.0.0.0'    volumes:      - .:/myapp    ports:      - "3000:3000"    depends_on:      - db

I really wonder why they didn't wrote that into the docs you linked. I opened a PR to add this.