简体   繁体   中英

docker-compose: run a command on a pgsql container

I am trying to run the following docker-compose file:

version: "3"
services:
  db:
    image: postgres
    container_name: pgsql
    environment:
      - foo=foo
      - bar=bar
    volumes:
      - ./sql/:/opt/sql
    command: bash /opt/sql/create-db.sql
#    command: ps -aux
  web:
    image: benit/debian-web
    container_name: web
    depends_on:
      - db
    ports:
      - 80:80
    volumes:
      - ./html:/var/www/html

I am encountering an error with the line:

command: bash /opt/sql/create-db.sql

It is because pgsql service is not started. It can be monitored with command: ps -aux

How can I run my script once pgsql service is started ?

You can use a volume to provide an initialization sql script:

version: "3"
services:
  db:
    image: postgres
    container_name: pgsql
    environment:
      - foo=foo
      - bar=bar
    volumes:
      - ./sql/:/opt/sql
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
  web:
    image: benit/debian-web
    container_name: web
    depends_on:
      - db
    ports:
      - 80:80
    volumes:
      - ./html:/var/www/html

This will work because original Posgresql dockerfile contains a script (that runs after Posrgres has been started) which will execute any *.sql files from /docker-entrypoint-initdb.d/ folder.

By mounting your local volume in that place, your sql files will be run at the right time.

It's actually mentioned in documentation for that image: https://hub.docker.com/_/postgres under the How to extend this image section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM