introduction
To execute a specific initialization file when starting a PostgreSQL container, you can use Docker'sTable of contents. The SQL file in this directory will be automatically executed when the container starts.
Here is how to modify the Docker Compose configuration file to execute initialization SQL scripts at startup:
Create an initialization SQL script file:
Create a SQL file in the project, for example, and write the SQL commands that need to be executed into it. Make sure that this SQL file contains the required database structure and data.
-- CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, username VARCHAR(50) NOT NULL, password VARCHAR(100) NOT NULL ); INSERT INTO users (username, password) VALUES ('admin', 'admin123');
Update Docker Compose configuration:
existIn the file, add
volumes
Configure, map the directory containing the initialization SQL script to the PostgreSQL containerTable of contents.
version: "3.8" services: postgresql: container_name: postgresql image: 172.:5000/postgres:15-alpine restart: always environment: POSTGRES_PASSWORD: dify POSTGRES_DB: dify PGDATA: /var/lib/postgresql/data/pgdata volumes: - ./volumes/db/test/data:/var/lib/postgresql/data - ./init-scripts:/ ports: - "5432:5432" networks: - ssrf_proxy_network networks: ssrf_proxy_network: driver: bridge internal: true
In the above configuration, I added a volumes entry - ./init-scripts:/, which maps the local directory ./init-scripts to the directory of the PostgreSQL container.
Start the PostgreSQL container:
Run the PostgreSQL container started by the following command and have it execute the initialization SQL script:
docker-compose up -d
The PostgreSQL container will start and automatically execute the SQL script file in the directory. In this way, the database will be initialized and the tables and data will be created.
Ensure that the naming of the SQL script file complies with PostgreSQL's execution order requirements (usually executed alphabetical). This allows the database to be automatically initialized every time the PostgreSQL container is started.
This is the article about the sample code of starting postgresql using docker compose. For more related content on starting postgresql with docker compose, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!