如何查找含指定字符串的Docker容器并执行exec命令
Got it, I’ve been in this exact spot—dealing with those pesky containers that have random suffixes tacked onto their base names. Here’s how you can ditch the hardcoded ihm and dynamically grab the full container name every time:
Basic Solution: Filter and Extract the Container Name
Use docker ps with filtering and formatting to pull the full name of your "ihm" container, then pass it directly to docker exec:
docker exec -it $(docker ps --filter "name=ihm" --format "{{.Names}}") bash
Breakdown of the command:
docker ps --filter "name=ihm": Filters running containers to only those with "ihm" anywhere in their name.--format "{{.Names}}": Tells Docker to output only the full container name (no extra clutter like status or ports).$(...): Command substitution—takes the output from thedocker pscommand and plugs it intodocker execas the target container name.
More Precise Filtering (Avoid Accidental Matches)
If you want to eliminate any chance of targeting the wrong container (say, another one that happens to have "ihm" in its name), narrow the filter to match containers starting with myApp_ihm:
docker exec -it $(docker ps --filter "name=^/myApp_ihm" --format "{{.Names}}") bash
The ^/ prefix ensures we only match containers whose name starts with myApp_ihm (the / accounts for Docker’s internal naming convention where container names are prefixed with a slash).
Alternative: Use Container ID Instead of Name
You can also target the container by its ID (often shorter and just as reliable) by switching the format string to {{.ID}}:
docker exec -it $(docker ps --filter "name=ihm" --format "{{.ID}}") bash
Bonus: Create an Alias for Repeated Use
If you run this command often, save yourself typing by adding an alias to your shell config (like ~/.bashrc or ~/.zshrc):
alias exec_ihm='docker exec -it $(docker ps --filter "name=^/myApp_ihm" --format "{{.Names}}") bash'
After adding that, run source ~/.bashrc (or your respective config file) to apply the change. Now you can just type exec_ihm to jump into the container instantly!
内容的提问来源于stack exchange,提问作者firasKoubaa

