รัน PHP บน Docker (Dockerfile) แบบง่ายๆ ใครก็ทำได้ จริงดิ???

PHP + Docker

ก่อนอื่นเราจะติดตั้ง Docker ที่เครื่องเราก่อน ซึ่งวิธีการติดตั้งนั้นก็ง่ายนิดเดียวแค่คลิกๆ เมื่อติดตั้งเสร็จแล้วเราก็มาเริ่มกันเลย

เราก็มาเริ่มเขียน php กันก่อนโดยเราจะเขียนทดสอบฟังก์ชั่น php แบบง่ายๆ ว่าสามารถใช้งานได้ไหม เสร็จแล้วบันทึกเป็น index.php

index.php

จากนั้นก็มาเขียน Dockerfile เสร็จแล้วบันทึกเป็น Dockerfile

  • FROM = เป็นการเลือก clone image ที่มีอยู่แล้วมาใช้งาน ดูเพิ่มเติม
  • COPY = [path ในเครื่องของเรา] [path ใน docker]
  • EXPOSE = กำหนด Port

เราก็จะได้โครงสร้าง project เราประมาณนี้ *อย่าลืมสร้าง folder src ภายใต้ folder project ของเราแล้วเอา index.php มาไว้ข้างในด้วยนะครับ

จากนั้นก็ใช้คำสั่ง docker build -t [ตั้งชื่อ image] เพื่อ build image ขึ้นมา

docker build -t hello-world

เสร็จแล้วเราก็จะได้ docker image มาพร้อมใช้งาน

docker images

จากนั้นเราก็สั่ง run image ด้วยคำสั่ง docker run -d -p 80:80 -v /Users/[path]/src/:/var/www/html/ [ชื่อ images] เพื่อที่จะได้ container ที่เราต้องการ

docker run -d -p 80:80 -v /Users/…/src/:/var/www/html/ hello-world

เราสามารถดูได้ว่ามี container ไหน run อยู่บ้างด้วยคำสั่ง docker ps

docker ps

เมื่อ container run อยู่เราก็สามารถใช้งานได้แล้ว

http://localhost

เราก็สามารถรัน php บน apache โดยใช้ docker ที่เครื่องของเราได้เลย เย้ๆ

แจกฟรี Source Code https://github.com/watcharinc/PHP-Dockerfile.git

Docker ทำให้ชีวิตเราสะบายขึ้นเยอะเลย ไม่ต้องติดตั้งอะไรให้วุ่นวาย เพียงแค่นี้เราก็ทำงานได้แล้ว

เดี๋ยวมีอะไรดีๆ จะมาแชร์ให้เรื่อยๆ ฝากติดตามกันด้วยนะครับ

Watcharin Chomphuteep

Written by

Sofrware Engineer at Ascend Group | Learning by Doing

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade