我是码头工人的新手。我已经扩展了PostgreSQL映像,并且能够在运行映像时创建新的数据库实例。我需要在shell脚本中创建表,该脚本将执行.sql文件。在运行PostgreSQL映像时,它说服务器没有启动?我们如何才能在PostgreSQL服务器在docker容器中启动后才能执行脚本?
Dockerfile:
FROM postgres:9.3
ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB docker
RUN apt-get update && apt-get install -y postgresql-9.3 postgresql-client-9.3 postgresql-contrib-9.3
ADD initialize.sh /home/MM0312/docker-entrypoint-initdb.d/initialize.sh
CMD ["/home/MM0312/docker-entrypoint-initdb.d/initialize.sh"]
initialize.sh
#!/bin/bash
set -e
set -x
echo "******PostgreSQL initialisation******"
gosu docker psql -h localhost -p 5432 -U docker -d $docker -a -f createDatabase.sql
createDatabase.sql文件
CREATE TABLE web_origins (
client_id character varying(36) NOT NULL,
value character varying(255)
);
答案 0 :(得分:24)
在official docker image of postgres的docker-entrypoint.sh脚本中写道:
psql+=( --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" )
echo
for f in /docker-entrypoint-initdb.d/*; do
case "$f" in
*.sh) echo "$0: running $f"; . "$f" ;;
*.sql) echo "$0: running $f"; "${psql[@]}" < "$f"; echo ;;
*.sql.gz) echo "$0: running $f"; gunzip -c "$f" | "${psql[@]}"; echo ;;
*) echo "$0: ignoring $f" ;;
esac
echo
done
因此,您希望在docker镜像中执行的每个.sql文件都可以放在该文件夹中。所以我的dockerfile看起来像
FROM postgres:9.3
ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB docker
ADD CreateDB.sql /docker-entrypoint-initdb.d/
我的CreateDB.sql的内容:
CREATE TABLE web_origins (
client_id character varying(36) NOT NULL,
value character varying(255)
);
所以我只需用:
启动我的容器docker run -d my-postgres
检查:
docker exec -it 6250aee43d12 bash
root@6250aee43d12:/# psql -h localhost -p 5432 -U docker -d docker
psql (9.3.13)
Type "help" for help.
docker=# \c
You are now connected to database "docker" as user "docker".
docker=# \dt
List of relations
Schema | Name | Type | Owner
--------+-------------+-------+--------
public | web_origins | table | docker
(1 row)
您可以找到mysql here in this blog的详细信息。