You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查找含指定字符串的Docker容器并执行exec命令

Dynamically Target Docker Containers by Partial Name

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 the docker ps command and plugs it into docker exec as 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:17:58