Which files are shared between docker container and host?

Abstract: Resolve file sharing between Docker containers and Ubuntu hosts by configuring bind mounts or named volumes for persistent, bidirectional data access.

Created: 2026-10-17 by
Files shared between a Docker container and the host are not automatic; they must be explicitly defined using volume mounts or bind mounts in the docker run command or docker-compose.yml file. By default, containers have an isolated filesystem, meaning any changes made inside the container are lost when it stops unless you persist data to the host machine. To share specific files or directories, you map a path on your Ubuntu host to a path within the container's filesystem, allowing bidirectional access to those resources.

Understanding Volume Types

There are two primary methods for sharing files between the host and a container: bind mounts and named volumes. Bind mounts map a specific directory or file from the host system directly into the container. This is useful when you want the container to read configuration files, source code, or logs located at exact paths on your host. For example, if you have a web application folder on your desktop, you can mount it so the container serves that live content. Named volumes, on the other hand, are managed by Docker itself. They are stored in a part of the host filesystem that Docker controls, typically at /var/lib/docker/volumes/. These are preferred for persistent data like databases because they are easier to back up, migrate, and manage independently of the host's directory structure. While bind mounts rely on the host's existing file permissions, named volumes provide a consistent interface regardless of the underlying host OS.

Using Bind Mounts for File Sharing

Bind mounts allow you to sync files between your Ubuntu host and the container in real-time. When you use a bind mount, any change made to the file on the host is immediately visible inside the container, and vice versa. This is particularly useful for development environments where you edit code on your host machine but need the container to execute it. To create a bind mount, you use the -v or --mount flag with the docker run command. The syntax requires specifying the host path followed by the container path, separated by a colon. Here is an example command that mounts a local directory called my-app into the container at /app:
docker run -it -v $(pwd)/my-app:/app ubuntu bash
In this example, $(pwd) expands to the current working directory on your host. If you modify a file inside my-app on your host, the container sees the update instantly. However, be aware that bind mounts inherit the permissions of the host files. If the container runs as a non-root user, it might not have write access to certain host files unless permissions are adjusted correctly.

Managing Permissions and Security

One common issue when sharing files is permission errors. Docker containers often run processes as the root user by default, which can lead to conflicts if the host files are owned by a different user. To resolve this, you can ensure that the user ID (UID) and group ID (GID) of the host user match the user inside the container. Alternatively, you can run the container with the same UID as your host user by passing environment variables or using the --user flag. Security is another consideration. Bind mounts give the container direct access to the host filesystem, which can be risky if the container is compromised. It is best practice to mount only the necessary directories and set them to read-only if the container does not need to write to them. You can achieve this by adding :ro to the end of the mount path in the -v argument. Fixing Mutagen/Docker Config Issues with DDEV and Mounting Code to /srv Directory provides further insight into how mounting configurations can impact performance and compatibility in complex setups.

Persisting Data with Named Volumes

For applications that generate data you want to keep, such as databases or logs, named volumes are the recommended approach. Unlike bind mounts, named volumes are not tied to a specific host directory structure, making them more portable. You can create a named volume using the docker volume create command and then attach it to a container.
docker volume create my-data-volume
docker run -it -v my-data-volume:/data ubuntu bash
This setup ensures that even if the container is removed, the data in my-data-volume persists. You can inspect these volumes using docker volume ls and manage them with standard Docker commands. This method abstracts away the host filesystem details, providing a cleaner separation between your application data and the host OS.

Docker Compose Configuration

When managing multiple services, docker-compose.yml simplifies the process of defining shared files. In the compose file, you define volumes under a top-level volumes key and reference them in individual services. This approach makes it easy to share configuration files or code across multiple containers without repeating long mount paths. For instance, you can define a volume for a database and another for application code, linking them to their respective services. This declarative style is easier to maintain and version control than manual docker run commands. It also allows for more complex configurations, such as mounting the same volume to multiple containers for data sharing. How to Change Host for Keycloak Docker Container: A Guide demonstrates how external configurations and host mappings interact with containerized applications, highlighting the importance of correct path mapping.

Frequently Asked Questions

Can I share a single file instead of a whole directory?

Yes, you can mount a single file using bind mounts by specifying the full path to the file on the host and the desired path inside the container. This is useful for mounting specific configuration files like nginx.conf or database credentials. Ensure the file exists on the host before starting the container, as Docker will not create it automatically.

What happens to shared files when the container stops?

If you use a bind mount, the files remain on the host filesystem unchanged, regardless of whether the container is running or stopped. If you use a named volume, the data is preserved in Docker's internal storage area and survives container removal. Only data written to the container's ephemeral layer is lost when the container is deleted, provided no volumes were used.

How do I fix permission denied errors when accessing mounted files?

Permission errors usually occur because the user inside the container does not match the owner of the host file. You can resolve this by changing the file ownership on the host to match the container's user ID, or by running the container with the --user flag set to your host user's UID. Adjusting file permissions with chmod on the host can also grant the necessary access.

Is there a performance difference between bind mounts and named volumes?

Bind mounts can sometimes suffer from slower performance on macOS and Windows due to the virtualization layer required to access the host filesystem. On Linux hosts, the performance difference is negligible. Named volumes are generally optimized for I/O operations and are preferred for high-throughput applications like databases, while bind mounts are better suited for development workflows requiring live code updates.

Can I mount a volume from a remote server?

Standard Docker volumes do not support direct mounting from remote servers over network protocols like NFS or SMB out of the box. You would need to set up a network filesystem client on the host machine first. Once the remote directory is mounted on the host, you can then use a bind mount to expose that local mount point to the container, effectively sharing remote files.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More