Building a Docker Container running Python + R + Rstan for use as an AWS Lambda Function


I’m attempting to create a AWS lambda function that executes a python script which also runs R and various R scripts (using rpy2). I had the following working dockerfile:

FROM python:3.8-slim-bullseye

ENV DEBIAN_FRONTEND=noninteractive

ENV TZ=:/etc/localtime
ENV PATH=/var/lang/bin:/usr/local/bin:/usr/bin/:/bin:/opt/bin
ENV LD_LIBRARY_PATH=/var/lang/lib:/lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib:/opt/lib

# Define custom function directory
ARG FUNCTION_DIR="/var/task"

# Install aws-lambda-cpp build dependencies + r
RUN apt-get update && \
  apt-get install -y \
  g++ \
  make \
  cmake \
  unzip \
  libcurl4-openssl-dev \
  r-base \

# Copy function code

# Install the function's dependencies using file requirements.txt
# from your project folder.

COPY requirements.txt  .
COPY . .
#install the python requirements
RUN pip3 install --target ${FUNCTION_DIR} -r requirements.txt

#install the r requirements
RUN R -e "install.packages('stringr')"
RUN R -e "install.packages('gtools')"
RUN R -e "install.packages('tidyr')"

# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
ENTRYPOINT [ "/usr/local/bin/python", "-m", "awslambdaric" ]
CMD [ "main.handler"]

this works for simple R scripts, but I would like to run a MCMC in rstan. Trying to install rstan simply using install.packages… appears to work (ie the dockerfile gets built), but then I get an ‘rstan not found’ in the logs when I try to run it. I know that ideally I should install R using a rocker image, but I haven’t been able to do that AND create a working lambda function that operates around my file.

Any help would be greatly appreciated!