Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
VGSources
Blog

How to Use the Docker Exec Command With Examples

A practical guide to docker exec: syntax, interactive shells, detached commands, environment and user options, shell operators, Docker Compose differences, and common errors.
Length8 min Posted Quest giverVGSources Team

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

docker exec runs a command inside an already running Docker container. Use docker exec -it CONTAINER sh for an interactive shell, a direct executable for a one-shot task, or -d when the task should continue in the background. The container must be running (and not paused), and the command you supply must exist inside its image.

What docker exec does

The command syntax is:

docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

CONTAINER is a container name or ID. COMMAND is an executable in that container, followed by any arguments. Docker starts a new process in the existing container; it does not create another container and it does not start a stopped one.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An exec process is available only while the container’s primary process (PID 1) is running. If PID 1 exits, the container stops and the exec process ends with it. Work launched with docker exec is not automatically recreated when the container is restarted.

Unless you override it, Docker starts the process in the container’s configured working directory. The command also sees environment variables that were present when the container was created. Options on the current invocation can add, override, or change that process context.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Before you run an exec command

  • Make sure Docker is running and the target container exists.
  • Make sure the container is running. A stopped container must be started with docker start before you can exec into it.
  • Make sure it is not paused. Docker rejects exec requests for a paused container; unpause it first.
  • Know which executable the image contains. Minimal images often include sh but not bash.
  • Use the container’s name or ID exactly as Docker reports it.

To see running containers and their names, use:

docker ps

Include stopped containers when locating a container that needs to be started:

docker ps -a

If the target is stopped, start it and then run the exec command:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
docker start mycontainer
docker exec mycontainer ls /

Run a one-shot command

A direct executable is the simplest form of docker exec. This example lists the root directory of a running container named mycontainer:

docker exec mycontainer ls /

Docker waits for the command in the foreground and returns its output and exit status to your terminal. This is useful for checking files, querying a process, or running a maintenance utility without opening a shell session.

The documented end-to-end pattern uses a long-running Alpine container:

docker run --name mycontainer -d -i -t alpine /bin/sh
docker exec mycontainer ls /

The first command starts the container in detached mode with an interactive shell as its primary process. The second command executes ls / in that already running container.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Open an interactive shell

For a shell prompt, combine interactive input and a pseudo-terminal:

docker exec -it mycontainer sh

-i keeps standard input open, while -t allocates a pseudo-terminal. Together, -it make an interactive session behave like a normal terminal. Type exit or press Ctrl-D to leave the shell; exiting this shell does not stop the container’s PID 1.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Use the shell that the image actually provides:

docker exec -it mycontainer bash

This works only when Bash is installed in the image. Alpine and other minimal images commonly provide sh instead, so use sh when bash returns an executable-not-found error.

If you only need to feed input to a command and do not need terminal features, -i can be used without -t:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
docker exec -i app cat

Run a command in the background

Add -d (or --detach) to return immediately while Docker runs the process in the background:

docker exec -d mycontainer touch /tmp/execWorks

Detached execution is appropriate for a task that should not occupy your terminal. Docker still ties the process to the container’s lifetime: if the container’s primary process stops, the detached exec process stops as well. Detaching does not turn the command into a service that Docker will restart independently.

Understand the important options

Option What it changes Example
-i, --interactive Keeps standard input open. docker exec -i app cat
-t, --tty Allocates a pseudo-terminal. docker exec -t app sh
-it Combines open input and a TTY for an interactive shell. docker exec -it app sh
-d, --detach Runs the command in the background. docker exec -d app touch /tmp/x
-e NAME=value, --env Adds or overrides an environment variable for this exec process. docker exec -e MODE=debug app env
--env-file FILE Reads variables from a file for this invocation. docker exec --env-file vars.list app env
-u, --user Runs as a username, numeric UID, or UID and GID. docker exec -u 1000 app id
-w, --workdir Sets the process working directory. docker exec -w /app app pwd
--privileged Gives the exec process extended privileges. docker exec --privileged app command

Options must appear before the container name. The executable and its arguments follow the container name.

Pass environment variables to one command

Variables inherited when the container was created remain available to an exec process. To add or override values for one invocation, use -e:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
docker exec -e VAR_A=1 -e VAR_B=2 mycontainer env

These values apply to the shell or process started by that command. They do not modify the environment of processes that were already running in the container, and they are not automatically retained for later exec calls.

For several variables, place assignments in a file and pass it with --env-file:

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)
docker exec --env-file vars.list mycontainer env

The file is read for that exec invocation; it is not a replacement for the container’s original environment configuration.

Choose the user and working directory

Change the working directory

Docker normally uses the container’s configured working directory. Override it with -w:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
docker exec -it -w /root mycontainer pwd

The command prints /root when that directory exists. If the path does not exist, the process fails rather than silently creating the directory.

Run under a specific identity

Use -u with a username, UID, or UID:GID pair:

docker exec -u 1000 app id
docker exec -u 1000:1000 app id
docker exec -u appuser app id

The requested account must be usable in the container. A numeric UID can work even when there is no matching name, but file permissions still apply to that UID and its group. Running as a different user can prevent access to files or directories that the container’s normal process can read.

Use pipes, redirects, variables, and command chains correctly

docker exec expects the command argument to be an executable. Shell syntax is not interpreted automatically. This is invalid because the quoted text is treated as the executable name:

docker exec -it my_container "echo a && echo b"

Start a shell explicitly and pass the command string to it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
docker exec -it my_container sh -c "echo a && echo b"

The same pattern is required for pipes, redirects, wildcard expansion, variable expansion, and other shell operators:

docker exec app sh -c 'grep ERROR /var/log/app.log | tail -n 20'

Use single or double quotes according to where expansion should happen. Text inside single quotes is passed as one argument by your local shell. With double quotes, your local shell may expand variables before Docker sends the command to the container. To expand a variable inside the container instead, protect the dollar sign from the local shell or place the complete script in a file inside the container.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

For a command that needs no shell features, call the executable directly. Direct execution avoids an extra shell layer and makes argument boundaries clearer:

docker exec app ls -la /app

Useful command patterns

Inspect files without opening a shell

docker exec app pwd
docker exec app ls -la /app

The first command shows the default working directory; the second supplies an explicit path so the result does not depend on that default.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Check the process identity and environment

docker exec app id
docker exec app env

These commands show which user and variables the exec process actually receives. Add -e when testing an override without changing other processes.

Run a multi-step diagnostic

docker exec app sh -c 'pwd; ls -la; echo "---"; id'

The semicolons and quoted script are interpreted by the container’s shell. Replace semicolons with && when later steps should run only if earlier steps succeed.

Perform a detached file operation

docker exec -d app touch /tmp/execWorks

Because the command is detached, its output is not presented as an interactive session. Use a later direct command to verify a result:

docker exec app ls -l /tmp/execWorks
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

docker exec versus docker compose exec

Both commands execute a process in an existing container, but they address that container differently.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Concern docker exec docker compose exec
Target A container name or ID. A Compose service name, such as web.
Interactive defaults You request equivalent shell behavior with -i -t. Interactive mode and a TTY are allocated by default.
Typical shell command docker exec -it web-container sh docker compose exec web sh
Disable TTY Do not pass -t. Pass -T, which disables TTY allocation.
Best fit Direct control of a known container. Projects managed through a Compose file, where the service name is the stable target.

Compose may create replacement containers as the project changes, so targeting the service avoids copying a generated container name into scripts or documentation. Use plain docker exec when you intentionally need a specific container ID or name.

For non-interactive automation with Compose, disable the default terminal allocation:

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
docker compose exec -T web sh -c 'command 1 | command 2'

Troubleshoot common failures

“No such container”

Check the exact spelling and whether you are using a name from the correct Docker context. Run docker ps -a, then use the displayed name or ID.

“Container is not running”

Start the container first:

docker start CONTAINER
docker exec CONTAINER COMMAND

If it stops again immediately, inspect why its primary process exits before attempting another exec session.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The container is paused

A paused container rejects exec requests. Unpause it, then retry:

docker unpause CONTAINER
docker exec CONTAINER COMMAND

“Executable file not found”

The requested command is not installed at the expected path. Try the image’s available shell, commonly sh for a minimal image, or call the utility by its full path if you know it.

A command chain runs as one literal name

Use sh -c (or another shell that exists in the image). Docker cannot interpret &&, pipes, redirects, or variable expansion when they are passed without a shell executable.

The command cannot read or write a file

Check the selected user with id, the file’s ownership and mode, and the working directory. Try -u or -w deliberately rather than adding privileges indiscriminately. --privileged grants extended privileges to the exec process and should be reserved for a specific requirement.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A detached process disappears after a restart

Exec processes are tied to the container’s primary process. They are not restarted automatically when the container restarts. If a task must always run, make it part of the image’s normal startup process or use an appropriate service and restart design instead of relying on a one-time detached exec.

A practical decision checklist

  • Need a prompt? Use docker exec -it CONTAINER sh (or bash if installed).
  • Need one result? Put the executable and arguments directly after the container name.
  • Need shell operators? Use sh -c and quote the script.
  • Need background execution? Add -d, then verify the result with a separate command.
  • Need temporary configuration? Use -e or --env-file; these affect only the new exec process.
  • Need a different account or directory? Use -u and -w, and verify permissions.
  • Working with Compose? Target the service with docker compose exec; add -T for scripts that must not allocate a TTY.
  • Command refused? Confirm the container is running, not paused, and contains the executable you requested.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.