Magnesium and its alloys have become potential implant materials in the future because of light weight, mechanical properties similar to natural bone, good biocompatibility, and degradability in physiological environment. However, due to the rapid corrosion and degradation of magnesium alloys in vivo, especially in the environment containing chloride ions, the application of magnesium alloys as implant materials has been limited. Therefore, improving the corrosion resistance of magnesium alloy and ensuring good biocompatibility is the main focus of the current research. In this study, hydroxyapatite coating was prepared on magnesium alloy surface using carboxymethyl cellulose-dopamine hydrogel as inducer to improve corrosion resistance and biocompatibility. Surface characterization techniques (scanning electron microscopy, Fourier-transformed infrared spectroscopy, energy dispersive X-ray spectroscopy- and X-ray diffraction) confirmed the formation of hydroxyapatite on the surface of AZ31 alloy. Corrosion resistance tests have proved the protective effect of Carboxymethyl cellulose-Dopamine/hydroxyapatite (CMC-DA/HA) coating on the surface of AZ31 alloy. According to MC3T3-E1 cell viability and Live/Dead staining, the coating also showed good biocompatibility. The results will provide new ideas for the biological application of magnesium alloys.