Setting up docker image with R and SQL server driv

2020-06-21 05:35发布

问题:

This is probably going to be an underspecified question, but as I’ve spent close to two days trying to get it to work I figured I might give it a try:

I am trying to set up a docker image that can comminicate with a SQL Server db through R (either using RODBC or odbc)

The problem I keep encountering seems to be that I fail to install (or locate) the neccisary SQL server drivers when establishing a connection, when running:

 con <- dbConnect(odbc(),
             Driver = "SQL Server",
             Server = "xxxx",
             Database = "xxxx",
             UID = "xxx",
             PWD = “xxxx")

Has anyone set up a similar Docker image ?

EDIT:

Here is my current dockerfile (I have tried multiple things but this one reproduces the error message)

    FROM rocker/r-ver:3.5.0

    RUN apt-get -qq update \
        && apt-get -qq dist-upgrade -y \
        && apt-get -qq install git unixodbc unixodbc-dev postgresql-9.5 odbc-postgresql libssl-dev sudo -y

    COPY . /usr/local/src/myscripts
    WORKDIR /usr/local/src/myscripts

    RUN R -e 'install.packages("odbc")'
    RUN R -e 'install.packages("plumber")'

    EXPOSE 8000

    CMD ["Rscript", "plumber.R"]

And running the container and executing odbc commands gives:

    > library('odbc')
    > con <- dbConnect(odbc(),
    +                    Driver = "SQL Server",
    +                    Server = "xx",
    +                    Database = "xx",
    +                    UID = "xx",
    +                    PWD = "xx")
    Error: nanodbc/nanodbc.cpp:950: 01000: [unixODBC][Driver Manager]Can't open lib 'SQL Server' : file not found

回答1:

In your Dockerfile you are installing ODBC drivers for PostgrSQL but not for MS SQL server. In a docker image that needed MS SQL I used the drivers from Microsoft:

FROM rocker/r-ver:3.5.1

RUN apt-get update \
 && apt-get install --yes --no-install-recommends \
        apt-transport-https \
        curl \
        gnupg \
        unixodbc-dev \
 && curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \
 && curl https://packages.microsoft.com/config/debian/9/prod.list > /etc/apt/sources.list.d/mssql-release.list \
 && apt-get update \
 && ACCEPT_EULA=Y apt-get install --yes --no-install-recommends msodbcsql17 \
 && install2.r odbc \
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/* \
 && rm -rf /tmp/*

In the R script I then used

con <- odbc::dbConnect(odbc::odbc(),
                 Driver = "ODBC Driver 17 for SQL Server",
                 Server = Sys.getenv("SERVER"),
                 Database = Sys.getenv("DB"),
                 UID = Sys.getenv("USER"),
                 PWD = Sys.getenv("PWD"))