Home Explore Blog CI



docker

2nd chunk of `content/get-started/docker-concepts/running-containers/persisting-container-data.md`
dcda06af1cb4758085f019bc9926e8d3b11cfffafd1f01e90000000100000886
- `docker volume rm <volume-name-or-id>` - remove a volume (only works when the volume is not attached to any containers)
- `docker volume prune` - remove all unused (unattached) volumes



## Try it out

In this guide, you’ll practice creating and using volumes to persist data created by a Postgres container. When the database runs, it stores files into the `/var/lib/postgresql/data` directory. By attaching the volume here, you will be able to restart the container multiple times while keeping the data.

### Use volumes

1. [Download and install](/get-started/get-docker/) Docker Desktop.

2. Start a container using the [Postgres image](https://hub.docker.com/_/postgres) with the following command:

    ```console
    $ docker run --name=db -e POSTGRES_PASSWORD=secret -d -v postgres_data:/var/lib/postgresql/data postgres
    ```

    This will start the database in the background, configure it with a password, and attach a volume to the directory PostgreSQL will persist the database files.

3. Connect to the database by using the following command:

    ```console
    $ docker exec -ti db psql -U postgres
    ```

4. In the PostgreSQL command line, run the following to create a database table and insert two records:

    ```text
    CREATE TABLE tasks (
        id SERIAL PRIMARY KEY,
        description VARCHAR(100)
    );
    INSERT INTO tasks (description) VALUES ('Finish work'), ('Have fun');
    ```

5. Verify the data is in the database by running the following in the PostgreSQL command line:

    ```text
    SELECT * FROM tasks;
    ```

    You should get output that looks like the following:

    ```text
     id | description
    ----+-------------
      1 | Finish work
      2 | Have fun
    (2 rows)
    ```

6. Exit out of the PostgreSQL shell by running the following command:

    ```console
    \q
    ```

7. Stop and remove the database container. Remember that, even though the container has been deleted, the data is persisted in the `postgres_data` volume.

    ```console
    $ docker stop db
    $ docker rm db
    ```

8. Start a new container by running the following command, attaching the same volume with the persisted data:

Title: Trying Out Docker Volumes: Persisting Data with Postgres
Summary
This section guides users through a hands-on exercise using Docker volumes to persist data for a Postgres container. It involves creating a Postgres container with a volume attached to its data directory, creating a database table and inserting data, then stopping and removing the container. Finally, a new container is started, re-attaching the same volume, proving that the data persists even after the original container is removed.