DEV Community

Weerasak Chongnguluam
Weerasak Chongnguluam

Posted on • Edited on

1 2

สั่งรันโปรแกรม บน docker container ที่กำลังรันอยู่

ถ้ามี container ที่รันอยู่แล้ว เช่น container ที่รัน MySQL อยู่ เช็คด้วย docker ps แล้วเจอแบบนี้

$ docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED       STATUS      PORTS                               NAMES
963b015eb1c1   mysql:8   "docker-entrypoint.s…"   4 weeks ago   Up 2 days   0.0.0.0:3306->3306/tcp, 33060/tcp   mysql_container
Enter fullscreen mode Exit fullscreen mode

แล้วถ้าเราอยากสั่งรันโปรแกรมอื่นๆ เช่นจะเรียกใช้ mysql client command ที่ติดตั้งไว้ภายใต้ container ที่กำลังรันอยู่นี้ด้วย เราสามารถใช้คำสั่ง docker exec ช่วยได้

เราลองดู help ของคำสั่งนี้กันก่อนด้วย docker help exec จะเจอแบบนี้

$ docker help exec

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

Run a command in a running container

Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a container
  -e, --env list             Set environment variables
      --env-file list        Read in a file of environment variables
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format: <name|uid>[:<group|gid>])
  -w, --workdir string       Working directory inside the container
Enter fullscreen mode Exit fullscreen mode

ซึ่งในกรณีนี้เราจะใช้ option -it เพราะต้องการให้ client ทำงานโดยมี interactive terminal รอรับคำสั่งที่เราจะพิมพ์ลงไปที่ mysql client ด้วย

ตัวอย่างการใช้งานในการเรียก mysql client ให้รันภายใต้ container ชื่อ mysql_container เป็นดังนี้

$ docker exec -it mysql_container mysql -p test
Enter fullscreen mode Exit fullscreen mode

นั่นคือสั่ง docker exec -it ตามด้วยชื่อ container mysql_container ตามด้วยคำสั่งและ option ของคำสั่งที่จะรัน mysql -p test เท่านี้เราก็รันคำสั่งที่ต้องการภายใต้ container ที่กำลังทำงานอยู่ได้แล้ว

Buy Me A Coffee

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay