How I could check connectivity in shell using an oneliner command without using netcat?
-1
votes
2
answers
144
views
In a docker image I want to avoid installing netcat in order to ping for db connectivity at my entrypoint script:
/bin/sh
MOODLE_DB_HOST="xxxx"
MOODLE_DB_PORT=80
function pingdb {
OK=0
for count in {1..100}; do
echo "Pinging database attempt ${count} into ${MOODLE_DB_HOST}:${MOODLE_DB_PORT}"
if $(nc -z ${MOODLE_DB_HOST} ${MOODLE_DB_PORT}) ; then
echo "Can connect into database"
OK=1
break
fi
sleep 5
done
echo "Is ok? "$OK
if [ $OK -eq 1 ]; then
echo "Database type: "${MOODLE_DB_TYPE}
echo "DB Type: "${MOODLE_DB_TYPE}
else
echo >&2 "Can't connect into database"
exit 1
fi
}
But instead, I want to use a nc
replacement for entrypoint script running upon docker images utilising php.
Is there an alternative?
The reason why I want to do this is because I have 2 Dockerfiles, one debian-based and one alpine based:
debian-based php image:
ARG PHP_VERSION="7.4"
FROM php:${PHP_VERSION}-fpm as base
RUN --mount=type=bind,from=mlocati/php-extension-installer:latest,source=/usr/bin/install-php-extensions,target=/usr/local/bin/install-php-extensions \
/usr/local/bin/install-php-extensions xmlrpc mbstring zip xml intl soap gd opcache &&\
echo "PHP_EXTENTION_DIR="$(php -i | grep extension_dir | cut -d " " -f 5) >> /etc/environment &&\
cat /etc/environment &&\
apt-get update &&\
apt-get install -y netcat &&\
apt-get autopurge -y &&\
apt-get autoremove -y &&\
apt-get autoclean &&\
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* cache/* /var/lib/log/* &&\
echo "max_input_vars=5000" > ${PHP_INI_DIR}/conf.d/moodle.ini
COPY ./scripts/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chown root:root /usr/local/bin/entrypoint.sh &&\
chmod +x /usr/local/bin/entrypoint.sh
ENTRYPOINT ["/bin/sh","/usr/local/bin/entrypoint.sh"]
CMD ["php-fpm"]
And alpine-based:
ARG PHP_VERSION="7.4"
FROM php:${PHP_VERSION}-fpm-alpine as base
RUN --mount=type=bind,from=mlocati/php-extension-installer:latest,source=/usr/bin/install-php-extensions,target=/usr/local/bin/install-php-extensions \
/usr/local/bin/install-php-extensions xmlrpc mbstring zip xml intl soap gd opcache &&\
apk update &&\
apk add netcat-openbsd &&\
rm -rf /var/cache/apk/* /var/tmp/* cache/* /var/lib/log/* &&\
echo "max_input_vars=5000" > ${PHP_INI_DIR}/conf.d/moodle.ini
COPY ./scripts/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chown root:root /usr/local/bin/entrypoint.sh &&\
chmod +x /usr/local/bin/entrypoint.sh
ENTRYPOINT ["/bin/sh","/usr/local/bin/entrypoint.sh"]
CMD ["php-fpm"]
And sometimes depending the argument of PHP_VERSION
may or may not the package for installing netcat do exist (or exist with different names). Also apk add
and apt-get
increases the build times significally as well.
So is there an alternative approach?
Asked by Dimitrios Desyllas
(1301 rep)
Jan 3, 2024, 09:07 PM
Last activity: Aug 8, 2024, 10:48 AM
Last activity: Aug 8, 2024, 10:48 AM