How can I apply Dockerfile multistage approach with Selenium and Firefox?

24 Views Asked by At

I'm trying to split my Dockerfile into multistage approach to reduce size. I'm using Selenium and firefox but copying from base image does not work.

find / -name firefox
/usr/local/lib/python3.11/site-packages/selenium/webdriver/firefox
/usr/lib/firefox
/usr/lib/firefox/firefox
/usr/bin/firefox

which firefox
/usr/bin/firefox

Dockerfile:

FROM python:3.11.4-alpine
COPY --from=base_image /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=base_image /usr/local/bin /usr/local/bin
COPY --from=base_image /usr/lib/firefox /usr/lib/firefox
COPY --from=base_image /usr/bin/firefox /usr/bin/firefox
COPY --from=base_image /project /project

selenium.py:

from selenium import webdriver

options = webdriver.FirefoxOptions()
#options.binary_location = "/usr/lib/firefox/firefox"
#options.binary_location = "/usr/bin/firefox/firefox-bin"
#options.binary_location = "/usr/bin/firefox"
service = webdriver.FirefoxService(executable_path=driver_path)
driver = webdriver.Firefox(service=service, options=options)

None of three diff bin paths works

How can i copy firefox files from base to final image and make Selenium works well?

1

There are 1 best solutions below

0
datawookie On

You can create a fairly light weight Docker image using this. It's hard to get more minimal than this. Cherry-picking dependencies from one stage to another will not be worth the pain.

Firefox will be installed onto your PATH, so there's no need to specify this path explicitly.

Dockerfile

FROM python:3.11.4-alpine

RUN apk add firefox && \
    pip install selenium==4.18.1

COPY selenium-firefox.py .

ENV MOZ_HEADLESS=1

CMD python3 selenium-firefox.py

selenium-firefox.py (A simple test script.)

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

options = Options()
options.headless = True
driver = webdriver.Firefox(options=options)

driver.get("http://google.com/")

print(driver.title)

driver.quit()

enter image description here