Search
Duplicate

Gracefully Stop in Docker

Created
3/9/2021, 3:25:00 PM
Tags
Empty
โ€ข
๋ฆฌ๋ˆ…์Šค์—์„œ kill์„ ํ•˜๋ฉด SIGTERM์„ ๋ฐœ์ƒ์‹œํ‚ค๊ณ , ์ด๋Š” docker stop๊ณผ ์œ ์‚ฌํ•˜๋‹ค.
โ€ข
๋ฆฌ๋ˆ…์Šค์—์„œ kill -9 ๋ฅผ ํ•˜๋ฉด SIGKILL์„ ๋ฐœ์ƒ์‹œํ‚ค๊ณ , ์ด๋Š” docker kill๊ณผ ์œ ์‚ฌํ•˜๋‹ค.
์›๋ž˜ SIGKILL์€ OOM์ด ๋ฐœ์ƒํ–ˆ๊ฑฐ๋‚˜, kill -9 ๋ช…๋ น์–ด๋กœ process๋ฅผ ์ข…๋ฃŒํ•  ๋•Œ ๋ฐœ์ƒ๋˜๋Š” ๋ฉ”์‹œ์ง€์ด๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์›๋ž˜ SIGKILL์€ ์–ด๋– ํ•œ ์ƒํ™ฉ์—์„œ๋„ ์ด๋ฅผ handlingํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด ์—†๋‹ค.
๋งŒ์•ฝ docker stop ๋ช…๋ น์–ด๋ฅผ ๋‚ด๋ฆฌ๋ฉด, ์ฒ˜์Œ์—๋Š” SIGTERM์„ ๋ณด๋‚ด๊ณ , 10์ดˆ ๊ฐ„ ๊ธฐ๋‹ค๋ ธ๋‹ค๊ฐ€ SIGKILL์„ ๋ณด๋‚ด๊ฒŒ ๋œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  docker kill์„ ๋‚ ๋ฆฌ๋ฉด Exit code 137 ์ฆ‰, SIGKILL์„ ๋ฐœ์ƒ์‹œํ‚ค๋ฉด์„œ ๋ชจ๋“  ํ”„๋กœ์„ธ์Šค๊ฐ€ ์ข…๋ฃŒ๋œ๋‹ค. ๋‹ค๋งŒ, docker kill โ€”signal์„ ํ†ตํ•ด์„œ ๋‚ด๊ฐ€ ์ง€์ •ํ•œ signal์„ ๋‚ ๋ฆด ์ˆ˜ ์žˆ๋‹ค.

Gracefully stopping in Python

โ€ข
๊ทธ๋Ÿฐ๋ฐ ์ด์ƒํ•˜๊ฒŒ try/finally ๊ตฌ๋ฌธ์—์„œ clearํ•˜๋„๋ก ์ฒ˜๋ฆฌํ•ด์ฃผ์—ˆ๋Š”๋ฐ, ์ œ๋Œ€๋กœ cachedir ์‚ญ์ œ๊ฐ€ ์•ˆ๋˜๋Š” ํ˜„์ƒ์„ ๋ฐœ๊ฒฌํ•จ. ์›์ธ์ด finally ๊ตฌ๋ฌธ์— ๋„๋‹ฌํ•˜์ง€ ๋ชปํ•ด์„œ์ธ์ง€, ์•„๋‹ˆ๋ฉด memory.clear()๊ฐ€ ์ •์ƒ์ž‘๋™ ํ•˜์ง€ ์•Š๋Š” ๊ฒƒ์ธ์ง€ ๋ชจ๋ฅด๊ฒ ์–ด์„œ ์ผ๋‹จ, clear() ์ดํ›„ ์ˆ˜๋™์œผ๋กœ shutil.rmtree๋ฅผ ์ด์šฉํ•ด์„œ ํ•œ ๋ฒˆ ๋” ํ•ด๋‹น dir๋ฅผ ์‚ญ์ œํ•ด์ฃผ๊ณ  ์žˆ์Œ.
โ€ข
์‚ดํŽด๋ณด๋‹ˆ, docker container๋“ฑ์„ stop์‹œํ‚ค๊ณ , 10์ดˆ ๋’ค์— exitcode 137 ์ฆ‰ sigkill์— ์˜ํ•ด์„œ process๊ฐ€ ๊ฐ•์ œ ์ข…๋ฃŒ๋˜๊ธฐ ๋•Œ๋ฌธ์—, finally์— ๋“ค์–ด๊ฐ€์ง€ ๋ชปํ•˜๋Š” ๊ฒƒ์œผ๋กœ ํŒŒ์•…๋จ.
โ€ข
์•„๋ž˜์˜ ๋งํฌ๋ฅผ ์ฐธ์กฐํ•˜์—ฌ, SIGINT๋‚˜ SIGTERM์„ ํ•ธ๋“ค๋ง ํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋ฐ”๊ฟ”์•ผํ• ๋“ฏ. https://stackoverflow.com/questions/18499497/how-to-process-sigterm-signal-gracefully https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python
import signal class GracefulKiller: kill_now = False def __init__(self): signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) def exit_gracefully(self, signum, frame): self.kill_now = True if __name__ == '__main__': killer = GracefulKiller() while not killer.kill_now: time.sleep(1) print("doing something in a loop ...") print("End of the program. I was killed gracefully :)")
Python

๊ฒฐ๋ก 

docker stop ๋ช…๋ น์–ด๊ฐ€ ๋‚ด๋ ค์กŒ์„ ๋•Œ, batch for loop์— ์œ„์˜ ์ฝ”๋“œ๋ฅผ ์ ์šฉํ•ด์„œ kill_now๊ฐ€ True์ผ ๋•Œ raise๋ฅผ ์‹œํ‚ค๋„๋กํ•˜๋ฉด, ์ตœ์ƒ๋‹จ์— ๊ฐ์‹ธ์ง„ try-finally์—์„œ ์ข…๋ฃŒ๊ณผ์ •์„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค. (๋‹จ, 1๋ฒˆ์˜ batch for loop ์‹คํ–‰์ด 10์ดˆ๊ฐ€ ๋„˜์–ด๊ฐ€๋ฉด ์•ˆ๋˜๊ณ , finally์—์„œ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ณผ์ •๋„ 10์ดˆ๊ฐ€ ๋„˜์–ด๊ฐ€๋ฉด ์•ˆ๋œ๋‹ค.)
TOP