📜  postgres docker init 脚本 (1)

📅  最后修改于: 2023-12-03 15:18:37.660000             🧑  作者: Mango

Postgres Docker Init Script

This guide explains how to use a bash script to initialize a PostgreSQL database using Docker.

Prerequisites
  • Docker installed on your machine. If you don't have Docker installed, you can download and install it from here.
Steps
  1. Create a new directory for your Dockerfile and initialization script, and cd into it.

  2. Create a new Dockerfile named Dockerfile with the following contents:

FROM postgres

COPY init.sql /docker-entrypoint-initdb.d/

This file sets up a new Docker image based on the latest official postgres image, and it copies a script named init.sql into the /docker-entrypoint-initdb.d/ directory. This script is executed when the container is started, and it will initialize the database with any necessary tables and data.

  1. Create a new bash script named init.sh with the following contents:
#!/bin/bash

docker build -t my-postgres .
docker run --name my-postgres-container -e POSTGRES_PASSWORD=mysecretpassword -d my-postgres

This script builds the Docker image from the Dockerfile and then runs a new container named my-postgres-container with the my-postgres image. This container is configured with a secure password for the postgres user.

  1. Create a new SQL script named init.sql with any necessary SQL commands to initialize your database schema and data.
CREATE TABLE IF NOT EXISTS users (
  id SERIAL PRIMARY KEY,
  name TEXT NOT NULL,
  email TEXT NOT NULL UNIQUE
);

INSERT INTO users (name, email) VALUES
  ('Alice', 'alice@example.com'),
  ('Bob', 'bob@example.com');

This script creates a new database table named users and inserts some sample data.

  1. Make the init.sh script executable:
chmod +x init.sh
  1. Run the init.sh script to create and start the container:
./init.sh

Congratulations! You now have a new PostgreSQL database running inside a Docker container with your schema and data initialized.

Conclusion

Using this simple bash script and Dockerfile, you can quickly and easily setup a PostgreSQL database with predefined tables and data for your application. This is a great solution for development, testing, and deployment scenarios where you need to quickly spin up new database instances.