Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

psql - How do I run a sql file of inserts through docker run?

Given a file with a SQL insert:

INSERT INTO countries (id, country_code, name)
VALUES
    (1, 'AF', 'Afghanistan'),
    (2, 'AL', 'Albania');

I would like to run the file by using the docker run command on a container that is running postgres.

I've tried this:

docker run -e domain="192.168.99.100" pg /bin/bash -c "psql -d whiteboard_api -a -f inserts_into_countries_table.sql"
psql: could not connect to server: Connection refused
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

you can see my image is pg:

capistrano:whiteboard_v2 jzollars$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
6b500bec9210        bbb                 "/usr/bin/supervisord"   4 weeks ago         Up 4 weeks          0.0.0.0:80->80/tcp       distracted_raman
c1e88f2695f5        wh                  "/usr/bin/supervisord"   4 weeks ago         Up 4 weeks          0.0.0.0:3000->3000/tcp   high_einstein
7e383e99bdc3        pg                  "/usr/lib/postgresql/"   4 weeks ago         Up 4 weeks          0.0.0.0:5432->5432/tcp   pg_test

How can I load this file and run it in a docker container using docker run?

question from:https://stackoverflow.com/questions/34688465/how-do-i-run-a-sql-file-of-inserts-through-docker-run

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

to execute commands against a running container use docker exec.

to copy a file (ex: dump.sql) into a container, use docker cp

So your approach might look something like this:

docker cp ./dump.sql pg_test:/docker-entrypoint-initdb.d/dump.sql
docker exec -u postgres pg_test psql postgres postgres -f docker-entrypoint-initdb.d/dump.sql

here it is in generic form:

docker cp ./localfile.sql containername:/container/path/file.sql
docker exec -u postgresuser containername psql dbname postgresuser -f /container/path/file.sql

And note that if you need to seed your database every time it is run, the folder /docker-entrypoint-initdb.d/ does have special significance, if you're using the offical postgres image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...