Copy Data from Postgres to CSV File Using Docker

Mar 11, 2021 min read

If you need to export data as a .csv file from Postgres and use Docker, here is a simple command to do just that.

Using the Docker exec command we can COPY data from a PostgreSQL container to a .csv file on the host machine.

docker exec -u <POSTGRES USER> <CONTAINER NAME> -d <POSTGRES DB> -c "COPY <TABLE> TO STDOUT WITH CSV HEADER" > <file.csv>

Example Use:

docker exec -u postgres db-container -d demo -c "COPY users TO STDOUT WITH CSV HEADER" > <users.csv>