3

I have the following docker-compose part

postgres:
    container_name: postgres
    image: postgres
    environment:
      POSTGRES_PASSWORD: "postgres"
    ports:
      - "15432:5432"
    volumes:
      - /root/database:/var/lib/postgresql/data
    networks:
      - production-network
    restart: unless-stopped
    depends_on:
      - rest-proxy
      - broker

What should I do to run a .sql file and restore the db as soon as I run docker-compose ?

  • Could you explain what's in the `.sql` file and what do you mean by restoring the DB? – Oresztesz Jan 27 '22 at 13:12
  • Create and inserts commands – ojoaovitoraraujo Jan 27 '22 at 13:34
  • If the backup is a plain SQL script, you can cause it to appear in some form in `/docker-entrypoint-initdb.d` when the container is _first_ created; also see [How to create User/Database in script for Docker Postgres](https://stackoverflow.com/questions/26598738/how-to-create-user-database-in-script-for-docker-postgres). More generally, [Backup/Restore a dockerized PostgreSQL database](https://stackoverflow.com/questions/24718706/backup-restore-a-dockerized-postgresql-database/29913462#29913462) discusses this topic. – David Maze Jan 27 '22 at 14:03

1 Answers1

4

Based on the docker image documentation you can include initialization scripts if you mount under /docker-entrypoint-initdb.d. It should work with both *.sql, *.sql.gz, or *.sh. So in your example, the compose file should look something like this:

postgres:
    container_name: postgres
    image: postgres
    environment:
      POSTGRES_PASSWORD: "postgres"
    ports:
      - "15432:5432"
    volumes:
      - /root/database:/var/lib/postgresql/data
      - /root/database-init/init-user-db.sql:/docker-entrypoint-initdb.d/init-user-db.sql:ro
    networks:
      - production-network
    restart: unless-stopped
    depends_on:
      - rest-proxy
      - broker

Assuming that init-user-db.sql file contains your initialization scripts.

Oresztesz
  • 2,294
  • 1
  • 15
  • 26