Reputation: 243
I am trying to insert data into postgres using docker.
I have a folder in my code named data which has insert
commands and has one file named init.sql.
I want to insert the data from init.sql
present in folder data to tables present in docker.
version: '3.1'
services:
postgres:
image: postgres:11.6-alpine
restart: always
ports:
- "5432:5432"
environment:
POSTGRES_PORT: 5432
volumes:
- ./tables:/docker-entrypoint-initdb.d/
- ./data:/var/lib/postgresql/data
volumes:
data: {}
I am trying this but I get the error:
initdb: directory "/var/lib/postgresql/data" exists but is not empty
I think I am not using the correct use case, I am new to docker compose.
But is there any way, my use case can get satisfied?
Upvotes: 2
Views: 12862
Reputation: 814
In my case, I was running a container using a non-empty host directory which caused issues on initialisation (in init.sql
):
> docker run --name pg --env POSTGRES_PASSWORD='pwd000' --env POSTGRES_USER='John' --env POSTGRES_DB='db' --publish 5432:5432 --volume ~/DockerDataVols/:/var/lib/postgresql/data
initdb: error: directory "/var/lib/postgresql/data" exists but is not empty
It contains a dot-prefixed/invisible file, perhaps due to it being a mount point.
Using a mount point directly as the data directory is not recommended.
Create a subdirectory under the mount point.
I deleted and recreated the host's folder and the error disappeared:
rm -rf ~/DockerDataVols
Upvotes: 0
Reputation: 39334
This is caused by an improper usage of the volumes
syntax for your named volume.
In order to mount a named volume you have to just use its name like this:
volumes:
- data:/var/lib/postgresql/data
If your syntax begins with a .
then it will be a bind mount from your host.
volumes:
- ./data:/var/lib/postgresql/data
The above code is mounting the host folder data
relative to where you your docker-compose.yml is located.
This docker-compose.yml should do what you expect.
version: '3.1'
services:
postgres:
image: postgres:11.6-alpine
restart: always
ports:
- "5432:5432"
environment:
POSTGRES_PORT: 5432
volumes:
- ./tables:/docker-entrypoint-initdb.d/
- data:/var/lib/postgresql/data
volumes:
data:
If for some reason your volume has been created already, with an empty or no database, your first step should be running:
docker-compose down --volumes
From the documentation:
-v, --volumes Remove named volumes declared in the `volumes`
section of the Compose file and anonymous volumes
attached to containers.
From: https://docs.docker.com/compose/reference/down/
Upvotes: 2