📅  最后修改于: 2023-12-03 15:18:37.660000             🧑  作者: Mango
This guide explains how to use a bash script to initialize a PostgreSQL database using Docker.
Create a new directory for your Dockerfile and initialization script, and cd into it.
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.
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.
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.
init.sh
script executable:chmod +x init.sh
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.
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.