How Do I Edit a File After I Shell into a Docker Container?

Once you’ve shelled into a Docker container using docker exec or docker attach, you might want to view or edit a file inside the container—for example, to change a config setting, debug an issue, or test a script in real time.

But since containers are often minimal and might not have text editors installed, you’ll need to know the right tools and commands to edit files effectively.

In this blog post, we’ll show you how to edit a file inside a running Docker container using different methods.


🧭 Step 1: Shell into the Container

Use the following command to open a shell session inside your running container:

docker exec -it <container_name_or_id> /bin/sh

Or, if the container has Bash:

docker exec -it <container_name_or_id> /bin/bash

Tip: You can find the container name with docker ps.


✏️ Step 2: Try a Built-In Text Editor

Option A: Use vi or vim (if available)

vi /path/to/file

But many lightweight images (like Alpine or BusyBox) don’t include vi/vim by default.

Option B: Use nano (if available)

nano /path/to/file

If you get a “command not found” error, you’ll need to install an editor.


🧰 Step 3: Install a Text Editor in the Container (Temporary)

To install an editor like vi or nano, you’ll need a package manager—if the container has one.

Debian/Ubuntu-based container:

apt update && apt install nano -y

Alpine-based container:

apk add nano

Now you can open files with:

nano /path/to/file

Note: Any changes you make inside a container are temporary unless you commit them or mount volumes.


🛑 Step 4: Alternative Method — Copy the File to Host, Edit, and Re-copy

If installing an editor isn’t an option, do the editing on your host machine:

Copy file from container to host:

docker cp <container_id>:/path/in/container/file.txt ./file.txt

Edit the file locally using any editor.

Then copy it back into the container:

docker cp ./file.txt <container_id>:/path/in/container/file.txt

💾 Step 5: Make Your Edits Persistent

Containers are ephemeral—changes are lost once the container is restarted unless:

  • You’re editing a mounted volume, or
  • You commit the container to create a new image:
docker commit <container_id> edited-container

Then run containers from that new image.


📝 Conclusion

Editing a file inside a Docker container is easy if you know the tools available. While some containers include vi or nano, many don’t—so you may need to install them or use docker cp to edit locally.

🔑 Summary

MethodWhen to Use
vi or nanoIf available inside container
apt install nanoIf using a Debian/Ubuntu-based image
docker cpIf editor is unavailable or limited
Commit or mount volumeTo make changes persistent
Sharing Is Caring:

Leave a Comment