1

I have a Django app running in Docker container. I'd like to populate my Postgres -database with some data when I run docker-compose up. I tried writing a sql -file:

# sql/fill_tables.sql

INSERT INTO person(name, gender)
    VALUES ('testUser', 'male');

This is my docker-compose.yml where I have added the sql to the volumes:

db:
    image: postgres
    volumes:
      - ./data/db:/var/lib/postgresql/data
      - ./sql/fill_tables.sql:/docker-entrypoint-initdb.d/fill_tables.sql
    env_file: .env 
    environment:
      - POSTGRES_DB=$DATABASE_NAME
      - POSTGRES_USER=$DATABASE_USER
      - POSTGRES_PASSWORD=$DATABASE_PASSWORD
    container_name: postgres_db  

This however doesn't do anything, the table in my database stays empty. How is this supposed to be done with Docker?

1 Answer 1

1

You can do it with docker-compose.yml, the reason it is not working right now is probably because you already have some data in /data.

If the /data volume exists and has some data, it will not be overwritten by docker-entrypoint-initdb.d/fill_tables.sql

I guess you could remove the line ./data/db:/var/lib/postgresql/data from your docker-compose.yml to see your database being fulfilled by fill_tables.sql

Sign up to request clarification or add additional context in comments.

6 Comments

I have no folder docker-entrypoint-initdb.d, should I create one manually? Do I create the folder inside my data/db/ or somewhere else? At the moment I have a folder called sql in my project folder and inside it the fill_tables.sql -file.
/docker-entrypoint-initdb.d/ is inside on your docker container your do not have to create it. Did you try to remove the ./data/db:/var/lib/postgresql/data from docker-compose.yml
Yes I tried that but the tables are not created and the app tells me I have not migrated my migrations. I guess I'd have to write a table creation sql also? Would prefer to just add some data to my existing tables when I run the container up..
How did you generate your fill_tables.sql ? Did you export the data or did you make yourself ? I guess what you sould do first create your database and add the data and then export the your database in a .sql file. then replace your current fill_tables.sql by the new one.
There is your issue. First export the database you have created then add the INSERT INTO person(name, gender) VALUES ('testUser', 'male'); You got the solution of your first question, I guess.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.