Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker commit - DB changes are no saved

Tags:

docker

lamp

I installed latest Docker CS, got a LAMP image from Docker Hub. I'm trying to create a DB in it and make a new image with that DB saved in it.

  1. Start the container: docker run --name mycontainer fauria/lamp This starts the Ubuntu-based container and starts Apache server. MySQL server is also running in the container.
  2. Access container shell: docker exec -i -t mycontainer bash
  3. Create a DB and run a few commands MySQL commands on it: mysql -u root CREATE DATABASE mydbname; USE mydbname; CREATE FUNCTION ... ...
  4. Stop the container: docker stop mycontainer
  5. Create an image: docker commitdocker ps -l -qmynickname/appname:v1
  6. Remove the container docker container rm mycontainer

Now I expected that if I run the container based on the new image I'd have the database there already. But it's not there. docker run --name mycontainer --rm -p 80:80 -e LOG_STDOUT=true -e LOG_STDERR=true -e LOG_LEVEL=debug -v /home/username/dev/appname/www:/var/www/html mynickname/appname:v1

What am I missing?

like image 841
flamey Avatar asked Mar 04 '26 13:03

flamey


2 Answers

The reason is that /var/lib/mysql is listed as a VOLUME in the Dockerfile.

The changes you make are retained between docker stop <yourcontainer> and docker start <yourcontainer> commands. But when you commit a container, each directory marked as VOLUME in the Dockerfile, is replaced with its original content. (This happens even if you haven't mounted an external volume to that directory.) See docker commit.

You can easily check that your other changes are kept in a commit by making changes somewhere outside the VOLUME directories. For instance, run date>/mydate inside the container and then commit it. When you then run a new container from that image, the file /mydate will still be there.

If you want to retain the the database changes, you can do that by cloning the repo and then remove the line VOLUME /var/lib/mysql from the Dockerfile. If you then build the new image and run it, it will retain your database changes when you commit the container.

Normally, in a production environment, you mount your database files either in a data container or on the host. This way the database data will be retained in the data container or on the host if you would commit the container.

like image 188
NZD Avatar answered Mar 06 '26 13:03

NZD


Having data being committed with the image is a useful scenario for testing. When using a prefabricated base image then you may have to remove the VOLUME entries however, see docker-copyedit for that.

like image 23
Guido U. Draheim Avatar answered Mar 06 '26 13:03

Guido U. Draheim