Snow
Snow

Reputation: 1138

\copy table via psql from local to Docker container from within the container

Disclaimer: Not talking about this.

How can I execute \copy command from psql when I'm inside the live docker container?

When I try \copy table from '/home/Snow/Documents/table.csv' with delimiter as ',' csv header; I get the error:

No such file or directory

Is there a different path I should write?

Upvotes: 1

Views: 3239

Answers (2)

Jeremy
Jeremy

Reputation: 6723

You would have to either copy the file to your docker container or mount the directory.

To copy the file, follow the procedure in the question to which you linked, something like:

docker cp /home/Snow/Documents/table.csv your_container:/

Then, from within your container, you could import access the file:

\copy table from '/table.csv' with delimiter as ',' csv header;

Alternatively, when you created the container, you could have added a volume with the -v option like:

docker run -v /home/Snow/Documents:/data postgres

and then your Documents directory would be at /data allowing you to import like this:

\copy table from '/data/table.csv' with delimiter as ',' csv header;

Upvotes: 1

Jim Jones
Jim Jones

Reputation: 19653

From outside the container you can import a file using psql with the following command:

$ cat table.csv | psql -h docker_container -d db -c \
"COPY table FROM STDIN WITH DELIMITER ',' CSV"
  • Replace docker_container with the IP or hostname of the container
  • In case your postgres isn't configured to accept external connections, change it in the postgres.conf file: e.g. listen_addresses = '*' to listen to all external connections.

Upvotes: 2

Related Questions