Create a Docker Image from a Running Linux System
Step 1: Archive the Root Filesystem
Run the following command to create an archive of your root filesystem while excluding special directories:
sudo tar -P --exclude=/proc --exclude=/sys --exclude=/dev --exclude=/tmp --exclude=/run --exclude=/mnt --exclude=/media -czf host_fs.tar.gz /
Command Breakdown & Analysis
tar
: The command-line utility for creating, extracting, and managing archive files.-P
: The option will create archives with absolute paths.--exclude=/proc --exclude=/sys --exclude=/dev --exclude=/tmp --exclude=/run --exclude=/mnt -exclude=/media
-czf host_fs.tar.gz /
: Creates a compressed tar archive namedhost_fs.tar.gz
from the root filesystem.
Directory Exclusions Explained
Directory | Reason for Exclusion |
---|---|
/proc | Virtual filesystem containing kernel and process information (non-persistent data). |
/sys | Kernel-related system information (dynamically generated). |
/dev | Device nodes, not normal files. |
/tmp | Temporary files that do not need to be backed up. |
/run | Runtime process data (e.g., PID files, sockets). |
/mnt | Mounted filesystems (could be external devices). |
/media | Mounted media like USBs and CDs. |
Step 2: Create the Dockerfile
Create a file named Dockerfile with the following content:
FROM scratch ADD host_fs.tar.gz / CMD ["/bin/bash"]
Step 3: Build the Docker Image
Run the following command to build the Docker image:
docker build -t host_based_image .
Step 4: Run a Container Based on This Image
Use this command to start a container using the newly created image:
docker run --rm -it host_based_image
Additional Considerations
- The
scratch
base image is empty, meaning your image will be an exact copy of your system. - Some Linux distributions require additional dependencies.
- If your Linux system uses
systemd
or other init systems, you may need special setup steps.