Attach docker volume using docker compose

I have created a docker volume from my Dockerfile , see below

FROM alpine:latest

.
.

VOLUME [ “/appdata” ]

I used the Dockerfile to build image for my application. I see a volume got created.

→ docker volume ls
DRIVER VOLUME NAME
local appdata

I then tried to use docker-compose for image building and docker container launch. My docker-compose.yaml look like this

version: “3”

services:
ocxapp:
image: testapp:v1
build:
context: .
container_name: testapp
volumes:
- appdata:/appdata
ports:
- “8000:8000”
- "8001:8001"
restart: always

volumes:
appdata:
driver: local

When I do docker-compose up, I see a new volume is getting created and not using the earlier “appdata” volume. Is there a way to use same volume ?

You probably want to remove the VOLUME declaration in your Dockerfile. It’s creating an anonymous volume at that mountpoint which is hiding your named volume, which is clearly not what you want.

I have tried commenting out VOLUME declaration from Dockerfile. I have created volume “appdata”, but still when I execute : docker-compose up -d , docker-compose create new volume app_appdata instead of the pre-existing volumeappdata .

Use the external property for this.

1 Like